A feature in C++ is the concept of constructor overloading in C++. Just like how functions can be overloaded with different variables inside the parameters (aka the brackets), C++ also supports the same thing with constructors. The compiler will automatically be able to recall which parameters match when it is compiling the code.

If you don’t know what a constructor does in C++, read Implementing a class with Object Orientated Object Programming Principles

Here is a basic example of applying constructor overloading in C++

Overloading constructors

</pre>
<pre>/*
Overloading class constructors
*/
#include <iostream>
using namespace std;

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// Area class declaration
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
class Area
{
int width, height;
public:
Area(); // Default constructor
Area(int, int); // Overloading constructor with variables in parameters
int total_area(); // Total area function
};

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
/// Default constructor implementation
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
Area::Area()
{
width = 10;
height = 10;
}

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// Overloading constructor implementation
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
Area::Area(int i, int j)
{
width = i;
height = j;
}

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// Total area function implementation
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
int Area::total_area()
{
return width * height;
}

int main()
{
Area rect1(3,4); // Overloading constructor Area(int i, int j)
Area rectb; // Default constructor Area()
// Display total area of rectangles
cout << "Area of rectangle 1" << rect1.total_area() << "\n";
cout << "Area of rectangle 2" << rectb.total_area() << "\n";
return 0;
}</iostream></pre>
<pre>
Share this post