Home »
C+ programs »
C++ constructor, destructor programs
C++ program to demonstrate example of Constructor Overloading
Learn about the Constructor Overloading in C++, how to implement Constructor Overloading in C++ program?
[Last updated : March 02, 2023]
In this program we will learn to create Constructor Overloading program in c++ programming language.
Constructor Overloading Program in C++
// C++ program to demonstrate example of
// Constructor Overloading
#include <iostream>
using namespace std;
//Class declaration.
class Demo {
//Private block to declare data member( X,Y )
//of integer type.
private:
int X;
int Y;
//Public blocks of member function to
//access data members.
public:
//Declaration of default constructor to
//initialize data members.
Demo();
//Declaration of parameterized constructor to
//initialize data members.
Demo(int a, int b);
//To display output onn screen.
void Display();
}; //End of class
//Definition of parameterized constructor.
Demo::Demo()
{
X = 10;
Y = 20;
}
//Definition of parameterized constructor.
Demo::Demo(int a, int b)
{
X = a;
Y = b;
}
//Definition of Display() member function.
void Demo::Display()
{
cout << endl
<< "X: " << X;
cout << endl
<< "Y: " << Y << endl;
}
int main()
{
Demo d1;
cout << "Default Constructor: " << endl;
cout << "Value after initialization : ";
d1.Display();
//Ctor automatically call when object is created.
Demo d2(30, 40);
cout << "Parameterized Constructor: " << endl;
cout << "Value after initialization : ";
d2.Display();
return 0;
}
Output
Default Constructor:
Value after initialization:
X: 10
Y: 20
Parameterized Constructor:
Value after initialization:
X: 30
Y: 40