-4

I have seen an object constructor (for class A for example) be called A() and A{} whats the difference? they both seem to do the same thing.

DanTheMan
  • 1
  • 1

1 Answers1

2

they both seem to do the same thing.

That is because they are two alternative syntaxes for the same thing.

whats the difference?

  • A{} did not exist until C++11.
  • In a variable declaration, A a() is syntactically ambiguous with a function declaration, and language rules say that it is a function declaration. A a{} works around this limitation because it is not syntax for a function declaration. Now, this is a difference between A a() and A a{} and a reason for existence of A a{}, but there is no need for inconsistency of not having A{} as well.

Another argument for having A{} in addition to A() is that A { arg1, arg2, ... }; is syntax for list initialization. For purposes of generic programming, it is necessary (or at least very useful) to also support an empty argument list: A{}.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • _`A a()` is syntactically ambiguous with a function declaration_: Sometimes it's called "most vexing parse" after Scott Meyers, IIRC. – rfx Aug 31 '17 at 13:18