gexicide
gexicide

Reputation: 40058

C++ "invalid constructor"

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

Answers (3)

hakuna matata
hakuna matata

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

Dima
Dima

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

Ed Heal
Ed Heal

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

Related Questions