Home > Net >  How does copy constructor call itself infinitely if it is passed by value
How does copy constructor call itself infinitely if it is passed by value

Time:06-17

I read that copy constructor is passed by reference in c because if the object is passed by value in the copy constructor then c will keep creating new object and call the copy constructor infinitely.

But i don't understand how does the copy constructor keep calling itself. Can anyone explain it to me? Thank you in advance

CodePudding user response:

If the copy constructor take it's parameter by value then how do you think the parameter of copy constructor get's constructed?

class X
{
public:
    X(X rhs);
    ...
};

X x;
X y(x); // calls copy constructor

In this code y is copy constructed with x. So the copy constructor is called. When the copy constructor is called rhs has to be constructed. How does that happen? By calling the copy constructor using x as the value. So calling the copy constructor has resulted in another call to the copy constructor. And (of course) that second copy constructor call results in a third copy constructor call. And so on, indefinitely.

CodePudding user response:

You simply can't declare a by-value "copy" constructor, it's ill-formed.

A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv-qualified) X and either there are no other parameters or else all other parameters have default arguments. A member function template is never instantiated to produce such a constructor signature.

[class.copy#5]

It also wouldn't be a copy constructor:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments.

[class.copy.ctor#1]

  • Related