Search code examples
c++constructorcopy-constructordefault-copy-constructor

Why ampersand is used in copy constructor?


Why do we pass object of a class by reference. When I remove ampersand (&) I get following error.

"Copy constructor of class A may not have parameter of type A"

What does this mean? may be compiler is not considering given a copy constructor and using default one.If this is that case why default one is being called. In short why we use ampersand and what will happen? if we don't.

class A
{
public:
    A()
    {

    }



    A(A& tmp)
    {
        id = 2*tmp.id;
    }

public:
    int id;
};


int main()
{
    A obj;
    obj.id = 10;

    A obj1(obj);  
    cout << obj1.id;
}

Solution

  • In C++, functions can take their parameters by value or by reference. If they take their parameters by value, that value must be copyable. If a copy constructor could take its parameter by value, then you would need a copy constructor to pass it its parameter, which would cause an endless loop.

    Consider:

    class MyInt
    {
        int m;
    
    public:
    
        MyInt(int i)
        {
            m = i;
        }
    
        MyInt(MyInt j)
        {
              j.m++;
              m = j.m;
        }
    };
    
    MyInt a(1);
    MyInt b(a);
    

    How can the compiler make this work? If it uses the default copy constructor, then why would it ever need to call my constructor? And if it uses my constructor, how does it prevent a.m from being incremented (which is clearly wrong, a should not be changed when it is passed by value) given that there's no code to give the constructor its own copy?