Search code examples
c++const-reference

Why a temp value cannot be used in a constructor with a const reference argument?


The code is as below

class A {};
class B
{
public:
    B(const A& a) {}
    void fun() {}
};

int main(int argc, char *argv[])
{
    B b(A());
    b.fun(); // Error: left of '.fun' must have class/struct/union  

    A a;
    B b2(a);
    b2.fun(); //Okay

    return 0;
}

Why?


Solution

  • The code

     B b(A());
    

    is not declaring an object of B, but rather a function declaration for a function b which returns an object of type B and takes a single (unnamed) argument which is a function returning type A(and taking no input). (Quoting from link below). Therefore, you saw that error.

    See C++ most vexing parse