Say I have a class A and have statements :
A a1(1);
A a2; a2(1);
What is the difference between the two statements?
I know first statement is straightforward but what is happening beside statement 2?
A a1(1);
This creates an instance a1 of class A by calling a constructor with argument 1.
A a2; a2(1);
This one's actually two statements. The first one, A a2;, creates an instance a2 of class A by calling the default constructor of A. The second one, a2(1);, then invokes A::operator() with parameter 1 (or produces an error in case A does not define operator()).
The difference is that, for most types, the second won't compile.
The first declares a variable and initialises it with value 1. Initialising from a value like this is known as direct initialisation.
The second declares a variable and default-initialises it; then it tries to call it like a function, which only works if it has a suitable overload of operator(). In that case, it does whatever that operator is defined to do.
Perhaps you meant:
A a2; a2 = 1;
to default-initialise the variable, then assign the value 1. For trivial types, this would have the same effect as the first. For types which define constructors and assignment operators, it would depend on how those are defined.
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