Thursday 12 July 2018

Why curly brace {} is preferred over normal brace ()

C++ 11 introduced a new syntax to initialize an object or variable by using brace {} initializer.
Let see why this syntax is more useful than normal brace () initializer.

class A{
public:
        void show() const{
                std::cout&lt&lt"Class A"&lt&ltstd::endl;
        }
};
class B{
public:
        B(const A& a): a(a){
        }
        const A& getA() const{
                return a;
        }
private:
        const A& a;
};

int main(){
#if 0
        B obj(A());
        const A& a = obj.getA();   // throws compilation error
#else
        B obj(A{});                // compiles without any complain
        const A& a = obj.getA();
#endif
        a.show();
}

The above code looks proper, but compiler is not satisfied with the code and throws error in obj.getA(). So, where is the problem ?

Lets see the line B obj(A()); here code looks valid but compiler is parsing this line as a function declaration obj which takes a function pointer that has no argument and returns object of class type A and return an object of type B.
So compiler is parsing the line B obj(A()); as B obj (A (*p) ());

No comments :

Post a Comment