Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/myscript/public_html/classes/classdb.php on line 42
What is Copy Constructor in C++ with Example

C++ Copy Constructor with Example

What is copy constructor and how to use it in C++?

Explanation

A copy constructor in C++ programming language is used to reproduce an identical copy of an original existing object.It is used to initialize one object from another of the same type.

Example :



#include<iostream>
using namespace std;
class copycon {
int copy_a,copy_b; // Variable Declaration
public:
copycon(int x,int y) {//Constructor with Argument
copy_a=x;
copy_b=y; // Assign Values In Constructor
}
void Display() {
cout<<"\nValues :"<< copy_a <<"\t"<< copy_b;
}
};
int main() {
copycon obj(10,20);
copycon obj2=obj; //Copy Constructor
cout<<"\nI am Constructor";
obj.Display(); // Constructor invoked.
cout<<"\nI am copy Constructor";
obj2.Display();
return 0;
}

Result :

I am Constructor
Values:10 20
I am Copy Constructor
Values:10 20

C++ Tutorial


Ask Questions

Ask Question