A copy constructor is a member function that initializes an object using another object of the same class. If you will not create your own copy constructor then the compiler creates a default copy constructor for you.
Syntax of copy constructor:
ClassName (const ClassName &old_obj);
Example,
#include<iostream>
using namespace std;
class Foo
{
private:
int x, y;
public:
Foo(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
Foo(const Foo &rOldObj)
{
x = rOldObj.x;
y = rOldObj.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Normal constructor is called here
Foo obj1(10, 15);
// Copy constructor is called here
Foo obj2 = obj1;
//Print obj1 values
cout << "obj1.x = " << obj1.getX();
cout << "\nobj1.y = " << obj1.getY();
//Print obj2 values
cout << "\n\nobj2.x = " << obj2.getX();
cout << "\nobj2.y = " << obj2.getY();
return 0;
}
Answer:
A copy constructor is a member function that initializes an object using another object of the same class. If you will not create your own copy constructor then the compiler creates a default copy constructor for you.
Syntax of copy constructor:
ClassName (const ClassName &old_obj);
Example,
Output: