1

Assume that I have "A" class. I want to create an "a" object using that class with 2 different ways, i.e:

A a();
A a = A();

What is the difference between them?

programmer
  • 91
  • 8

1 Answers1

2

A a(); is not a variable declaration, it is a function declaration. It declares a function a that takes no parameters and returns an A.

A a = A(); is a variable declaration and initialization. It declares a variable a of type A and initializes it from the temp object that is created by explicitly calling A's default constructor. The simpler way to do this is A a; (note the lack of parenthesis!), which a smart compiler is likely to optimize A a = A(); into anyway. If you want to explicitly call the default constructor (if one is present), use curly brackets instead of parenthesis: A a{};

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    *which a smart compiler is likely to optimize A a = A(); into anyway.* starting in C++17 it is mandated to be the same. *thank you guaranteed copy elision* – NathanOliver Sep 04 '19 at 19:27