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.
Asked
Active
Viewed 88 times
-4

DanTheMan
- 1
- 1
-
1What does your C++ book say on this subject matter? – Sam Varshavchik Aug 31 '17 at 10:43
-
See here: http://en.cppreference.com/w/cpp/language/initialization – Richard Critten Aug 31 '17 at 10:44
-
spend more time on reading constructors, you will get the answer yourself. – secretgenes Aug 31 '17 at 10:44
-
Why am I having trouble finding a duplicate? – StoryTeller - Unslander Monica Aug 31 '17 at 10:45
-
1@StoryTeller Looked for a duplicate myself, I suspect in the past these type of questions have been closed as too broad / read a book. – Richard Critten Aug 31 '17 at 10:47
-
How about an example, that would help a lot – Gerhard Stein Aug 31 '17 at 10:49
1 Answers
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 betweenA a()
andA a{}
and a reason for existence ofA a{}
, but there is no need for inconsistency of not havingA{}
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