Overloaded Expression - Constructor Overloading

Constructor Overloading

Constructors, used to create instances of an object, may also be overloaded in some object oriented programming languages. Because in many languages the constructor’s name is predetermined by the name of the class, it would seem that there can be only one constructor. Whenever multiple constructors are needed, they are implemented as overloaded functions. A default constructor takes no parameters, instantiating the object members with a value zero. For example, a default constructor for a restaurant bill object written in C++ might set the Tip to 15%:

Bill { tip = 15.0; total = 0.0; }

The drawback to this is that it takes two steps to change the value of the created Bill object. The following shows creation and changing the values within the main program:

Bill cafe; cafe.tip = 10.00; cafe.total = 4.00;

By overloading the constructor, one could pass the tip and total as parameters at creation. This shows the overloaded constructor with two parameters:

Bill(double setTip, double setTotal) { tip = setTip; total = setTotal; }

Now a function that creates a new Bill object could pass two values into the constructor and set the data members in one step. The following shows creation and setting the values:

Bill cafe(10.00, 4.00);

This can be useful in increasing program efficiency and reducing code length.

Read more about this topic:  Overloaded Expression