Search code examples
c++visual-c++constructorfunction-parameter

C++ Compiler Error C2751 - What exactly causes it?


I am wrestling with the C2751 compiler error and don't quite understand what exactly causes it. The following little code produces the error:

#include <iostream>  

class A {
public:
    A () { std::cout << "A constructed" << std::endl; };
    static A giveA () { return A (); }
};

class  B {
public:
    B (const A& a) { std::cout << "B constructed" << std::endl; }
};


int main () {

    B b1 = B (A::giveA ()); // works
    B b2 (B (A::giveA ())); // C2751
    B b3 (A::giveA ()); // works

}

Compiler output:

consoleapplication1.cpp(21): error C2751: 'A::giveA': the name of a function parameter cannot be qualified

Why can't I call the constructor explicitly for b2?


Solution

  • It's the problem of the most vexing parse. Compiling under clang gives a full diagnostic:

    <source>:18:17: error: parameter declarator cannot be qualified
        B b2 (B (A::giveA ())); // C2751
                 ~~~^
    
    <source>:18:10: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
        B b2 (B (A::giveA ())); // C2751
             ^~~~~~~~~~~~~~~~~
    
    <source>:18:11: note: add a pair of parentheses to declare a variable
        B b2 (B (A::giveA ())); // C2751
              ^
              (              )
    1 warning and 1 error generated.
    Compiler exited with result code 1
    

    Doing as the compiler suggests fixes it:

    B b2 ((B (A::giveA ()))); // no error