
Constructors
A constructor is a member function that is executed automatically whenever an object is created. There are two restrictions regarding it. First, the name of the constructor has to be name of the class. Second, it cannot have any return type, not even void. When such a constructor is present, it is automatically invoked when an object is declared.
For example,
class employee
{
public :
employee ( ) ;
employee ( long ) ;
employee ( long, char * ) ;
} ;
employee A ; // calls first constructor
employee B ( 15362 ) ; // calls second constructor
employee B ( 15362, "Naik" ) ; // calls third constructor
There are three constructors in the class employee. The first, which takes no arguments, is used to create objects which are not initialized. The second, which takes one argument, is used to create objects and initialize them. The third constructor, which takes two arguments, is also used to create objects and initialize them to specific values.
C++ compiler has an implicit constructor ( default constructor ) which creates objects, even though it was not defined in the class.
employee ( ) { }
It contains the empty body and does not do anything.
This works fine as long as we do not use any other constructors in the class. However, once we define a constructor, we must also define the default constructor. This constructor will not do anything and is defined just to satisfy the compiler.
Constructors with Default Arguments
It is possible to define constructors with default arguments. It means that if the constructor is defined with n parameters, we can invoke it with less than n parameters specified in the call.
For example,
Date ( int d, int m, y = 2007 ) ;
This constructor has three parameters. Parameter number three is initialized with a value 2007. Now we can call the constructor in two possible ways.
Date ( 15, 3, 2006 ) ;
Date ( 15, 3 ) ;