Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 320
gexicide Avatar asked Aug 10 '12 15:08

gexicide


People also ask

Which is not a valid constructor in C++?

1 Answer. A constructor cannot specify any return type, not even void. A constructor cannot be final, static or abstract.

What happens when a constructor fails?

Constructors don't have a return type, so it's not possible to use error codes. The best way to signal constructor failure is therefore to throw an exception. If you don't have or won't use exceptions, here's a work-around. If a constructor fails, the constructor can put the object into a "zombie" state.

How do you initialize a constructor?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.

What is constructor in C with example?

A Constructor in C is used in the memory management of C++programming. It allows built-in data types like int, float and user-defined data types such as class. Constructor in Object-oriented programming initializes the variable of a user-defined data type. Constructor helps in the creation of an object.


1 Answers

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.

like image 196
Dima Avatar answered Sep 29 '22 13:09

Dima