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.
#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; }
Total : 35 Total : 35To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions