Copy Constructor 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. A copy constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument.

Syntax :
   class_Name(className old_object)

Example :
   student(student o)

A copy constructor is a constructor that initializes an object using another object of the same class. It creates a copy of the original object, which is a duplicate of the original object with the same data. In this program, the class math has two constructors - a parameterized constructor and a copy constructor. The parameterized constructor takes two integer arguments and initializes the private data members of the class. The copy constructor takes an object of the math class as a parameter and initializes the private data members with the values of the object passed.

In the main() function, two objects of the math class, o and o1, are created. o is initialized using the parameterized constructor with arguments 10 and 25. o1 is initialized using the copy constructor and is passed the o object as a parameter. The add() member function is called on both objects to display the sum of their private data members. The output of the program will display the sum of the private data members of the o object and o1 object.

Source Code

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

Output

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