2

I'm new at C++ and I'm currently learning about constructors. Say I have a class Dog with a constructor:

class Dog{
    Dog(){
        std::cout << "Constructor called!
    }
};

I know that in C++ there are different ways(if I'm not mistaken) we can create an object, for instance:

1- Dog dog;
2- Dog dog = Dog();
3- Dog *dog = new Dog;
4- Dog *dog = new Dog();
5- Dog dog();

But here is the thing: statements from 1 to 4 all call the constructor, but the statement number 5 doesn't and I can figure out why.

Do you have any idea why the fifth statement doesn't call the class constructor? Thanks.

user3885884
  • 415
  • 3
  • 6
  • 13

2 Answers2

5

5 is an example of C++'s most vexing parse.

Dog dog();

This declares a function named dog that accepts no parameters and returns a Dog. To avoid the most vexing parse (and if you are using C++11), you can do:

Dog dog{};

And semantically (at least until C++17), Dog dog = Dog(); will first create a temporary object (Dog()), and then move construct (or copy construct, if Dog class has no move constructor) a named object (dog) from it. Although compilers might optimize the move away, this statement does have different semantics from the rest.

If I remember correctly, since C++17, P0135r0 will change the semantics of Dog dog = Dog(); so that it has the same meaning as Dog dog;.

EDIT: As pointed out by @LightnessRacesinOrbit in the comments, Dog dog(); is vexing, but not quite the most vexing parse. Dog dog(Dog()); is true most vexing parse. Dog dog(); is just a, well, plain declaration, I guess.

Zizheng Tai
  • 6,170
  • 28
  • 79
  • @LightnessRacesinOrbit Hmm, I could be mistaken. *Anything that can be parsed as a function declaration will be* -- isn't this most vexing parse? – Zizheng Tai Jul 06 '16 at 11:33
  • 1
    No, that is a simple fact of the language. It leads to the most vexing parse (`Dog dog(Dog())`, per the article you linked to) but this is not quite that. I like to call it the "lesser vexing parse" as a compromise ;) – Lightness Races in Orbit Jul 06 '16 at 11:34
2
Dog dog();

This line does not create an object, it's parsed as a function declaration.

If I remember correctly, it is called most vexing parse.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207