Constructor Overloading in C++ Programming


The constructors are special function named after the class and without a return type, and are used to construct objects. Constructors, like function, can take input parameters. Constructors are used to initialize objects. The constructor overloading in C++ means to more than one constructor in an instance class.

A constructor is a special member function of a class that is used to initialize the data members of the object. In C++, we can have multiple constructors in a class, which is known as constructor overloading.

In this program, we have defined three constructors for the math class: a default constructor, a parameterized constructor, and a copy constructor. The default constructor initializes the data members a and b to 0. The parameterized constructor takes two integer arguments and initializes the data members with the values of those arguments. The copy constructor takes an object of the math class as an argument and initializes the data members with the values of the corresponding data members of that object.

The add() member function of the math class calculates the sum of the a and b data members and prints the result. In the main() function, we create three objects of the math class using the three different constructors. We call the add() member function on each object to display the sum of the a and b data members.

Source Code

#include<iostream>
using namespace std;
//Constructor Overloading in C++ Programming
 
class math
{
private:
    int a,b,c;
public:
    math()//Default Constructor
    {
        a=0;
        b=0;
    }
    math(int x,int y)//Parameterized Constructor
    {
        a=x;
        b=y;
    }
    math(math &x) //Copy Constructor
    {
        a=x.a;
        b=x.b;
    }
    void add()
    {
        c=a+b;
        cout<<"Total : "<<c<<endl;
    }
};
int main()
{
    math o1;
    math o2(10,25);
    math o3(o2);
    o1.add();
    o2.add();
    o3.add();
    return 0;
}
 

Output

Total : 0
Total : 35
Total : 35
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples