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.
- No arguments, defaults x and y to zero.
- One arguement assigns x and defaults y to zero.
- One arugeument defaults x to zero and assigns y. I'm not sure if I am setting up the class right. I get the follwing error:
pair1::pair1(double)
andpair1::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; }
};
I'm not sure that having default arguments except for the (0,0) case is of any use, but something like this could work:
Use:
That's easy
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()
andSetY()
to set the X and Y separately, and make distinction by the name of the function.The problem is that the compiler has no way to distinguish
and
Indeed, they are the same thing except for the name of the parameter. For example:
This is called ambiguous overloading.
These are exactly same constructor. Different parameter name doesn't make any difference. All that matters for overloading is, the type(s) and number of types, and their ordering.