C++ - Copy Constructor
Copy Constructor are also the special type of constructors in C++ and they have got a specfic syntax.
The syntax is,
const classname& classname(const classname& other);
There are many ways copy constructors gets called.
1. When the object gets copied explicitly or implicitly
2. When the object gets initialized.
Source Code
class MyClass
{
private:
int m;
int a;
int b;
public:
MyClass() : a(10), b(20), m(30)
{
};
// Syntax for copy constructor
MyClass(const MyClass &other)
{
this->a = other.a;
this->b = other.b;
this->m = other.m;
}
// Syntax for assignment operator
const MyClass& operator = (const MyClass &other)
{
this->a = other.a;
this->b = other.b;
this->m = other.m;
return *this;
}
};
void main()
{
MyClass a; // calls default constructor
MyClass c; // calls default constructor
MyClass b = a; // calls copy constructor
c = b; // calls assignment operator
}
|