I am confused about the different syntax used for instantiating an object.
This is my class:
class Object
{
private:
int field = 0;
public:
Object() = default; // Just for testing.
~Object() = default; // Just for testing.
Object( const Object& obj ) = default; // Just for testing.
};
This is main method:
int main()
{
Object b(); // ???
Object c{}; // default
Object d = Object(); // default
Object e = Object{}; // default
Object f ( Object() ); // ???
Object g { Object() }; // default
Object a; // default but avoid
Object h ( Object() ); // ???
Object i { Object{} }; // default
Object j = i; // copy
Object k( j ); // copy
Object l{ k }; // copy
Object m = { l }; // copy
Object n = ( m ); // copy
auto o = Object(); // default
auto p = Object{}; // default
return 0;
}
I have no problem with the one's marked default
or copy
. I just want to know, which constructor is called for the one's with ???
as the default one is not called. Has it something to do with ()
initialization, as it can be seen.
I know this may not be important, but I am suspicious about it.
Can anyone help!
All the three declarations are function declarations, but not variable definition (as you expected).
Object b();
declares a function named b
, which takes nothing and returns Object
.
Object f ( Object() );
declares a function named f
, which takes a unnamed parameter whose type is a function returning Object
and taking nothing (i.e. Object()
), and returns Object
. Similarly for Object h ( Object() );
.
As the workaround, for Object b();
you can
Object b;
Object b{}; // since C++11
For Object f ( Object() );
you can
Object f ( ( Object() ) );
Object f ( Object{} ); // since C++11
Object f { Object{} }; // since C++11
Object f { Object() }; // since C++11
See most vexing parse for more.