C ++ 11 Difference in Constructors (curly braces)

I am new to C ++ and noticed 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 the header file as

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

Can you explain to me what is the difference between the three ways to create an object? And why does the second method create a compiler error?

+4
source share
2 answers

The paths are one and three default constructor calls.

MyClass c3{};

It is a new initialization syntax called uniform initialization . This is called default initialization. However:

MyClass c2();

Declares a function c2that does not accept parameters with a return type MyClass.

+6
source

MyClass c2();

- - . gotw.

- .

, ++ 11, , , , {}, .

+7

Source: https://habr.com/ru/post/1545243/


All Articles