Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this call the default constructor?

struct X {     X()    { std::cout << "X()\n";    }     X(int) { std::cout << "X(int)\n"; } };  const int answer = 42;  int main() {     X(answer); } 

I would have expected this to print either

  • X(int), because X(answer); could be interpreted as a cast from int to X, or
  • nothing at all, because X(answer); could be interpreted as the declaration of a variable.

However, it prints X(), and I have no idea why X(answer); would call the default constructor.

BONUS POINTS: What would I have to change to get a temporary instead of a variable declaration?

like image 328
fredoverflow Avatar asked Jul 27 '12 15:07

fredoverflow


People also ask

Why is it called a default constructor?

This constructor is called the default constructor because it is run "by default;" if there is no initializer, then this constructor is used. The default constructor is used regardless of where a variable is defined.

Why do we call default constructor in Java?

The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.

When the default constructor is called?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

Will default constructor be always called?

A constructor is automatically called when an object is created. It must be placed in public section of class. If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body).


1 Answers

nothing at all, because X(answer); could be interpreted as the declaration of a variable.

Your answer is hidden in here. If you declare a variable, you invoke its default ctor (if non-POD and all that stuff).

On your edit: To get a temporary, you have a few options:

  • (X(answer));
  • (X)answer;
  • static_cast<X>(answer)
  • X{answer}; (C++11)
  • []{ return X(answer); }(); (C++11, may incur copy)
  • void(), X(answer);
  • X((void(),answer));
  • true ? X(answer) : X();
  • if(X(answer), false){}
  • for(;X(answer), false;);
  • X(+answer);
like image 200
Xeo Avatar answered Sep 20 '22 13:09

Xeo