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:

When a constructor has been parameterized, the object declaration statement such as:

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:

  1. By calling the constructor explicitly, or
  2. By calling the constructor implicitly

The following declaration illustrates the first method (explicitly):

This statement creates an integer object in1 and passes the value 0 and 100 to it.

Now, the second method(implicit) is depicted below:

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:

The output of the above program would be:

Now, the constructor functions can also be defined as inline functions as illustrated below:

Also, the parameters of a constructor can be of any type except that of the class to which it belongs. For example:

The above example is ILLEGAL.

However, a constructor can accept a reference to its own class as a parameter. For example:

The above example is VALID.

In such cases, the constructor is called the copy constructor.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *