Reputation: 40058
when I am trying to create a class which has a constructor which takes an object of that class by value, like for example:
class X{
X(){}
X(X x){} //Error!
};
then g++ complains the following for the second constructor:
error: invalid constructor; you probably meant ‘X (const X&)’
Dear compiler, no, I did not mean a const reference. This time, I wanted to do what I wrote: to pass the parameter x by value! Why is this invalid?
Upvotes: 13
Views: 4963
Reputation: 3327
You are trying to implement a copy constructor, which works only by passing a reference to the object you want to copy.
Upvotes: 1
Reputation: 39389
You are trying to create a copy constructor, and a copy constructor must take a reference. Otherwise, when you pass the x into the constructor by value, the compiler will have to create a temporary copy of x, for which it will need to call the copy constructor, for which it will need to create a temporary copy.... ad infinium.
So a copy constructor must take its argument by reference to prevent infinite recursion.
Upvotes: 25
Reputation: 59997
Because
X(X x){} //Error!
needs a copy constructor. i.e itself i.e. recursive. i.e. When does it end?!
Upvotes: 7