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

129 Views Asked by At
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)'

4

There are 4 best solutions below

0
On BEST ANSWER

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.

0
On

The constructor with three default args conflicts with your no-arg constructor.

0
On

The constructor is ambigious. The compiler is unable to understand constructor you want to call if you construct Complex with no arguments: whether it is the default constructor

Complex();

or the constructor with three arguments all defaulted:

Complex(float =10  , float = 20, float = 30);

Both of these constructors would match if you do

Complex c;

or

new Complex();
0
On

The error message lays it out pretty clearly.

The problem is that because all 3 arguments are defaulted, the compiler has no idea how to deduce what function overload you're talking about.

// default constructor, or 3 defaulted floats?
Complex a;