1. Constructors
■ Special member function which enables an object to initialize itself when it is created
■ Its name is same as the class name
■ Constructor definition outside class:
class integer
{ int m,n;
public:
integer(void);
……….
};
integer :: integer (void)
{ m=0; n=0;}
■ Constructor definition within class:
class integer
{ int m,n;
public:
integer(void)
{ m=0; n=0;}
……….
};
Characteristics of constructor:
■ They should be declared in the public section
■ They are invoked automatically when the objects are created
■ They do not have return types, not even void and therefore, and they cannot return
values
■ They cannot be inherited, though a derived class can call the base class
■ They can have default arguments
■ Constructors cannot be virtual functions
2. Parameterized Constructors
class integer
{ int m,n;
public:
integer (int x, int y);
……….
};
integer :: integer (int x, int y)
{
m=x;
n=y;
}
■ Explicit constructor call: integer int1=integer(1,2);
■ Implicit constructor call: integer int1(1,2);
3. Multiple Constructors in a Class
class code
{ int id;
public: code( ){ id=5;}
code (int a) { id=a; }
code( int a, int b) {id=a+b; }
};
In this class ‘code’ we have three constructors:
Page | 1
, i) code(): This is a constructor with no parameters.
ii) code(int a): This is a constructor with one parameter.
iii) code(int a, int b): This is a constructor with two parameters.
Hence, multiple constructors may be used in a class as shown in the above code.
4. Questions
Q.1) What is a constructor? Why is it used?
Q.2) What are the rules for creating a constructor?
Q.3) How can parameterized constructors be implemented in C++?
Q.4) How can multiple constructors be implemented in C++?
5. Constructors with Default Arguments
class Demo
{ private:
int X,Y;
public:
Demo()
{ X = 0;
Y = 0;
cout << endl << "Constructor Called";
}
Demo(int X, int Y=20)
{
this->X = X;
this->Y = Y;
cout << endl << "Constructor Called";
}
void putValues()
{
cout << endl << "Value of X : " << X;
cout << endl << "Value of Y : " << Y << endl;
}
};
void main()
{
clrscr();
Demo d1= Demo(10);
cout << endl <<"D1 Value Are : ";
d1.putValues();
Demo d2= Demo(30,40);
cout << endl <<"D2 Value Are : ";
d2.putValues();
getch();
}
Output:
Constructor Called
D1 Value Are :
Value of X : 10
Value of Y : 20
Page | 2