Parameterized Constructors in C++
The constructor integer(), defined in the previous section (Constructors in C++), initializes the data members of all the objects to zero. However, in practice it may be necessary to initialize the various data elements of different objects with different values when the are created. C++ permits us to achieve this objective by passing arguments to the constructor function when the objects are created. The constructors that can take the arguments are called parameterized constructors.
The constructor integer() may be modified to take arguments as shown below:
class integer { private: int m, n; public: integer(int x, int y); //parameterized constructor ... ... }; integer :: integer(int x, int y) { m = x; n = y; }
When a constructor has been parameterized, the object declaration statement such as:
integer in1;
may not work. We must pass the initial values as arguments to the constructor function when an object is declared. This can be done in two ways:
- By calling the constructor explicitly, or
- By calling the constructor implicitly
The following declaration illustrates the first method (explicitly):
integer in1 = integer(0,100); //explicit call
This statement creates an integer object in1 and passes the value 0 and 100 to it.
Now, the second method(implicit) is depicted below:
integer in1(0, 100); //implicit call
This method, sometimes called the shorthand method, is used very often as it looks shorter, looks better and is easy to implement.
Remember, when the constructor is parameterized, we must provide appropriate argument for the constructor.
Program given below demonstrates the passing of arguments to the constructor functions:
#include<iostream.h> class integer { private: int m, n; public: integer(int, int); //constructor declared void display(void) { cout << "m = " << m << endl; cout << "n = " << n << endl; } }; integer :: integer(int x, int y) //constructor defined { m = x; n = y; } void main() { integer in1(0, 100); //IMPLICIT call integer in2 = integer(23,76); //EXPLICIT call cout << "Object1" << endl; in1.display(); cout << "Object2" << endl; in2.display(); }
The output of the above program would be:
Object1 m = 0 n = 100 Object2 m = 23 n = 76
Now, the constructor functions can also be defined as inline functions as illustrated below:
class integer { private: int m, n; public: integer(int x, int y) //inline constructor { m = x; n = y; } ... ... };
Also, the parameters of a constructor can be of any type except that of the class to which it belongs. For example:
class A { private: ... ... public: A(A); }; //Is ILLEGAL
The above example is ILLEGAL.
However, a constructor can accept a reference to its own class as a parameter. For example:
class A { private: ... ... public: A(&A); } //Is VALID
The above example is VALID.
In such cases, the constructor is called the copy constructor.