× Back Initialization and assignment copy constructor
Next Topic → ← Previous Topic

Initialization vs assignment

Copy constructor

The copy constructor can be defined explicitly by the programmer using the following syntax ↓

                   
class MyClass {
public:
    // Default constructor
    MyClass();

    // Copy constructor
    MyClass(MyClass &obj); // we have to pass object as reference
    /* MyClass(MyClass &obj) {
        x = obj.x;
    } */ // can be defined inside the class
private:
    int x;
    int* ptr;
};

// Implementation of the copy constructor
MyClass::MyClass(MyClass &obj) {
    x = obj.x;
}
                   
               
                       
#include <iostream>
using namespace std;

class MyClass
{
public:
    // Default constructor
    MyClass();

    // Copy constructor
    MyClass(MyClass &other);

    // Get value of x
    int getX();

    // Set value of x
    void setX(int value);

private:
    int x;
};

// Default constructor
MyClass::MyClass()
{
    x = 0;
}

// Copy constructor
MyClass::MyClass(MyClass &other)
{
    x = other.x;
}

// Get value of x
int MyClass::getX()
{
    return x;
}

// Set value of x
void MyClass::setX(int value)
{
    x = value;
}

int main()
{
    // Create an object of MyClass
    MyClass obj1;

    // Set the value of x
    obj1.setX(5);

    // Create a copy of obj1
    MyClass obj2 = obj1;

    // Print the value of x for obj1 and obj2
    cout << "obj1.x = " << obj1.getX() << endl;
    cout << "obj2.x = " << obj2.getX() << endl;

    // Change the value of x for obj1
    obj1.setX(10);

    // Print the value of x for obj1 and obj2 again
    cout << "obj1.x = " << obj1.getX() << endl;
    cout << "obj2.x = " << obj2.getX() << endl;

    return 0;
}                               
                        
                    
                   
#include <iostream>
using namespace std;
class Number
{
    int a;

public:
    Number()
    {
        a = 0;
    }
    Number(int num)
    {
        a = num;
    }

    // When no copy constructor is found, compiler supplies its own copy constructor
    Number(Number &obj)
    {
        cout << "Copy constructor" << endl;
        a = obj.a;
    }
    void display()
    {
        cout << "The number for this object is " << a << endl;
    }
};

int main()
{
    Number x, y, z(45), z2;
    x.display();
    y.display();
    z.display();

    Number z1(z); // copy constructor invoked
    z1.display();

    z2 = z;        // copy constructor not invoked
    Number z3 = z; // now in this time copy constructor will be invoked cuse we are just created this object
    // copy constructor don't get invoked when the object is already created and later we are just assinging some value or another object.

    return 0;
}