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
, orX(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?
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.
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.
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() .
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With