Reputation: 38417
I've been taking a look at how to create an instance of a class in C++. There seem to be several ways of doing this:
ClassExample classExample1;
ClassExample classExample2();
ClassExample classExample3(void);
ClassExample classExample4 = ClassExample();
1 and 4 call the default constructors. When I use 2 and 3, I can't seem to refer to the variables and they are not initialised. In the debugger, they are stepped over. Why is this? Are these the same? What is the difference? Is there a preferred option?
When we have parameters to pass there are two ways of doing this:
ClassExample classExample1(true, 1, "");
ClassExample classExample2 = ClassExample(true, 1, "");
Again, is there a difference? what is the preferred option?
UPDATE
C++ 11 also introduced this form of initialization:
ClassExample classExample2{ };
which is the equivelant of:
ClassExample classExample2();
Upvotes: 3
Views: 510
Reputation: 254431
1 is the preferred option - it initialises the variable directly.
2 and 3 declare functions, not variables, which is why you don't observe variables.
4 is (more-or-less) equivalent to 1, but it's unnecessarily verbose, conceptually more complex, and imposes an extra requirement on the type. In principle, it creates a temporary object, initialises the variable by copying or moving it, then destroys the temporary. In practice this will (usually) be elided, giving the same outcome as the first option; but it won't compile unless the type has an accessible copy or move-constructor.
Upvotes: 3
Reputation: 47784
There's no question of preferred option
ClassExample classExample2();
and
ClassExample classExample3(void);
declares a function returning ClassExample
object
Upvotes: 8