Search code examples
c++c++11visual-c++-2012

why cant i initialize 3 default parameters at a time in c++


class Complex 
{
private:

float rp, ip;
//const int a=10;
//static int b;
//static const int c = 50;
public:
Complex();
//Complex(float );
/*Complex(float,float);*/
Complex(float , float = 20, float = 30);
} 

The above code works fine but when i try to have 3 default parameters

class Complex
{
private:
float rp, ip;
//const int a=10;//static int b;//static const int c = 50;
public:
Complex();
//Complex(float );
/*Complex(float,float);*/
Complex(float =10  , float = 20, float = 30);
} 

I get the below error -

main.cpp(12): error C2668: 'Complex::Complex' : ambiguous call to
overloaded function complex.h(15): could be 'Complex::Complex(float,float,float)' complex.h(12): or 'Complex::Complex(void)'


Solution

  • This fails because the compiler cannot know which of the two different functions you mean when you write

    Complex c;
    

    Does that call

    Complex();
    

    or

    Complex(float,float,float);
    

    with the three default values?

    You can get around this by removing the Complex() constructor and have default construction be handled by the Complex(float,float,float) constructor with the three default values.