Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Difference in Constructors (Braces)

I am quite new to C++ and have observed, that the following lines of code act differently

MyClass c1;
c1.do_work() //works
MyClass c2();
c2.do_work() //compiler error c2228: left side is not a class, structure, or union.
MyClass c3{};
c3.do_work() //works

with a header file as

class MyClass {
public:
    MyClass();
    void do_work();
};

Can you explain me, what the difference between the three ways of creating the object is? And why does the second way produce a compiler error?

like image 398
Ennosigaeon Avatar asked Dec 12 '22 05:12

Ennosigaeon


1 Answers

The second version

MyClass c2();

is a function declaration - see the most vexing parse and gotw.

The first case is default initialisation.

The last case, new to C++11, will call the default constructor, if there is one, since even though it looks like an initialiser list {}, it's empty.

like image 188
doctorlove Avatar answered Dec 28 '22 09:12

doctorlove