I am creating a pair1 class for a x and y Cartesian coordinate system. x and y are doubles. I need to have 3 constructors.
pair1::pair1(double) and pair1::pair1(double) cannot be overloaded.My class:
class pair1
{
private:
double x;
double y;
public:
pair1(){ x = 0.0, y = 0.0; }
pair1( double a ){ x = a; y =0.0; }
pair1(double b){ x = 0.0; y = b; }
};
1) no arguments, defaults x and y to zero.
That's easy
2) one arguement assigns x and defaults y to zero.
3) one arugeument defaults x to zero and assigns y.
That's a problem. How do you know, when you only have one parameter, which of the two is meant to be called? That's why you get a compilation error.
Instead - use the default constructor (the one with no parameters), full constructor (the one with both), if needed, and SetX() and SetY() to set the X and Y separately, and make distinction by the name of the function.
class pair1
{
private:
double x;
double y;
public:
pair1( double a=0.0, double b=0.0 ){ x = a; y =b; };
// default value 0.0 allows to only
// set x, and leave y to be the default,
// or leave them both default.
void SetX(double a) { x=a;};
void SetY(double b) { y=b;};
};
The problem is that the compiler has no way to distinguish
pair1(double a)
and
pair1(double b)
Indeed, they are the same thing except for the name of the parameter. For example:
pair1 myPair1(123.456); // Which constructor should be called?
This is called ambiguous overloading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With