3

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();
Muhammad Rehan Saeed
  • 35,627
  • 39
  • 202
  • 311

2 Answers2

8

There's no question of preferred option

ClassExample classExample2();

and

ClassExample classExample3(void);

declares a function returning ClassExample object

P0W
  • 46,614
  • 9
  • 72
  • 119
3

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 2
    Is it guaranteed optimization? Take a look here: http://stackoverflow.com/questions/24510052/which-constructor-is-called-in-the-following-code – Neil Kirk Jul 01 '14 at 12:16
  • 1
    @NeilKirk: No, it's not guaranteed. There may be compilers that don't bother with optimisation, but you wouldn't use them for any practical purpose. – Mike Seymour Jul 01 '14 at 12:17
  • 1
    [This](http://stackoverflow.com/a/1758221/1870232) says that standard says _T = x; to be equivalent to saying T(x);. (§12.8.15, pg. 211)_ – P0W Jul 01 '14 at 12:26
  • 2
    @P0W: I assume those should be declarations, meaning `T y = x;` is equivalent to `T y(x);`. I don't see what that has to do with the question; it doesn't add another option since `ClassExample e5(ClassExample());` is also a function declaration, and even if it did, you'd still use option 1 rather than messing around with temporaries. – Mike Seymour Jul 01 '14 at 12:29