Search code examples
c++copy-constructormost-vexing-parse

C++ copy constructor failure


I had a look at the various options suggested as questions that Stackoverflow thought might already have an answer, but nothing I saw came close.

Sample code:

#include <math.h>

class v2
{
public:
    float x;
    float y;

    v2(float angle) : x(cos(angle)), y(sin(angle))          {}
    v2(const v2 &v) : x(v.x), y(v.y)                        {}
};

int main(int argc, char **argv)
{
    float const angle(1.0f);
    v2 const test1(angle);
    v2 const test2(v2(angle));
    v2 const test3(test1);

    float const x1(test1.x);
    float const y1(test1.y);

    float const x2(test2.x);                // These two lines fail, claiming left of .x must have class type.
    float const y2(test2.y);

    float const x3(test3.x);
    float const y3(test3.y);

    return 0;
}

This is with MSVC, from VS 2010. The creation of test2 compiles correctly, but access of its members fails, claiming test2 does not have a class type.

As far as I can see everything is correct, the copy constructor takes a const reference, so it should work just fine with the temporary being used.

So what is the cause of the error?


Solution

  • The compiler thinks that test2 is a function! Read about the most vexing parse.

    You can resolve this with either of these two :

    v2 const test2((v2(angle)));  // before C++11
    
    v2 const test2{v2(angle)};    // C++11 uniform initialization