Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 341
dgnuff Avatar asked Nov 29 '22 10:11

dgnuff


2 Answers

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
like image 72
Manos Nikolaidis Avatar answered Dec 11 '22 01:12

Manos Nikolaidis


You have fallen victim to the most vexing parse. In your code, you've declared test2 as a function. One way to fix this is to add an extra set of parenthesis: v2 const test2((v2(angle)));.

like image 29
MooseBoys Avatar answered Dec 11 '22 01:12

MooseBoys