Constructor: A member function with thesame name as its class is called Constructor and it is used to initialize the objects of that class type with a legal initial value.
If a class has a constructor, each object of that class will be initialized before
any use is made of the object.
Need for Constructors: A variable, an array or a structure in C++ can be initialized at the time of their declaration.
Eg:
int a=10;
int a[3]= {5,10,15};
struct student
{
int rno;
float m1,m2,m3;
};
student s1={1,55.0,90.5,80.0};
But this type of initialization does not work for a class because the class members have their associated access specifiers. They might not be available to the outside world(outside their class). A Constructor is used to initialize the objects of the class being created(automatically called by the compiler).
Difference between a constructor and an ordinary member function:
Constructor:
Name: Name of the Class.
Purpose: Initialize the object when it is being created.Call Return type: Implicit Should not keep .
Member Function:
Name: Any Valid Identifier.
Purpose: For any general purpose.
Call Return type: Explicit Must be there at least void.
Declaration and Definition: A constructor is a member function of a class with the same name as that of its class name. A constructor is defined like other member functions of a class. It can be defined either inside the class definition or outside the class definition.
Eg:
class X
{ int i;
public:
int j,k;
X ( ) //Constructor
{
i = j = k = 0;
}
------
//Other members
------
};
This simple constructor (X::X ( ) ) is as an inline member function. Constructors can be written as outline functions also as it is shown below:
class X
{
int i ;
public:
int j, k ;
X ( ); //Only
constructor declaration. ------ //Other members
------
};
X :: X ( ) //Constructor defined outside
{
i = j = k = 0;
}
Generally constructor will be defined under public section, which can be available to non members also. But it can also be defined under private or protected. A private or protected constructor is not available to the non-member functions. Ie With a private or protected constructor, you cannot create an object of the same class in a non-member function.
CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )