0

What is the difference between defining an object of class "Person" by using its default constructor following two different ways:

Method 1:

Person person = Person();

Method 2:

Person person();

When I initialized some variables inside the default constructor and tried to access those variables or set those variables by get/set methods in the main routine, I got compilation error in Method 2, but Method 1 works.

Thanks.

Community
  • 1
  • 1
manojg
  • 59
  • 8

1 Answers1

11
Person person = Person();

This declares a Person object called person. It initialises this object with a temporary object created by Person(). That means it'll invoke the copy/move constructor of Person (which will probably be elided).

Person person();

This declares a function called person that returns a Person object. This is not a declaration of an object.

You most likely want this instead:

Person person;

This declares a Person object called person which is default constructed.

You may want to use the new "uniform" initialisation syntax introduced in C++11, which avoids the ambiguities between variable and function declarations:

Person person{};

And finally, if you're AAA-minded, you may want to use the style proposed by Herb Sutter:

auto person = Person{};
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324