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

StackOverflow https://stackoverflow.com/questions/16027982

  •  04-04-2022
  •  | 
  •  

Question

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?

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top