Overloading Constructors

Overloading Constructors
Overloading Constructors
CONCEPT

Multiple constructors with the same name may exist in a C++ program, as long as their parameter lists are different. This is one type of constructor which is known as overloading constructor.

EXPLANATION

Any class member function may be overloaded, including the constructor. One constructor might take an integer argument, for example, while another constructor takes a double. There could even be a third constructor taking two integers. As long as each constructor has a different list of parameters, the compiler can tell them apart. 
Below the Program declares and uses a class named Sale, which has two constructors. The first has a parameter that accepts a sales tax rate. The second, which is for tax-exempt sales, has no parameters. It sets the tax rate to 0. A constructor like this, which has no parameters, is called a default constructor.

PROGRAM

1 // This program demonstrates the use of overloaded constructors.
2 #include <iostream>
3 #include <iomanip>
4 using namespace std;
5
6 // Sale class declaration
7 class Sale
8 {
9 private:
10 double taxRate;
11
12 public:
13 Sale(double rate) // Constructor with 1 parameter
14 { taxRate = rate; // handles taxable sales
15 }
16
17 Sale() // Default constructor
18 { taxRate = 0; // handles tax-exempt sales
19 }
20
21 double calcSaleTotal(double cost)
22 { double total = cost + cost*taxRate;
23 return total;
24 }
25 };
26
27 int main()
28 {
29 Sale cashier1(.06); // Define a Sale object with 6% sales tax
30 Sale cashier2; // Define a tax-exempt Sale object
31
32 // Format the output
33 cout << fixed << showpoint << setprecision(2);
35 // Get and display the total sale price for two $24.95 sales
36 cout << "\nWith a 0.06 sales tax rate, the total\n";
37 cout << "of the $24.95 sale is $";
38 cout << cashier1.calcSaleTotal(24.95) << endl;
39
40 cout << "\nOn a tax-exempt purchase, the total\n";
41 cout << "of the $24.95 sale is, of course, $";
42 cout << cashier2.calcSaleTotal(24.95) << endl;
43 return 0;
44 }
Program Output
With a 0.06 sales tax rate, the total
of the $24.95 sale is $26.45

On a tax-exempt purchase, the total
of the $24.95 sale is, of course, $24.95

Notice on lines 29 and 30 of Program how the two Sale objects are defined.
Sale cashier1(.06);
Sale cashier2;
There is a pair of parentheses after the name cashier1 to hold the value being sent to the 1-parameter constructor. However, there are no parentheses after the name cashier2, which sends no arguments. In C++ when an object is defined using the default constructor, instead of passing arguments, there must not be any parentheses.
Sale cashier2; // Correct
Sale cashier2(); // Wrong!

Previous
Next Post »