Search code examples
c++default-parameters

Function Default Parameters in C++


I've been asked this question in a job interview, and even after compiling it, I still don't understand the outcome...

I have the following class:

class Point
{
    public:
    Point(double x = 0, double y = 0) { m_X = x; m_Y = y; }

    double m_X, m_Y;
};

and main.cpp is:

int main()
{
    double a = 1, r = 1, xCoord = 5, yCoord = 7;

    Point p = (a+r*xCoord , a+r*yCoord);

    cout<<"X = "<<p.m_X<<" Y = "<<p.m_Y<<endl;

    return 0;
}

The data members of class p are getting the values:

m_X = a+r*yCoord, m_Y = 0

Now, why is that?


Solution

  • Because of the comma operator and the non-explicit constructor. The expression (a + r * xCoord , a + r * yCoord) is an application of the comma operator and has the value a + r * yCoord, and now the one-parameter implicit form of your Point constructor is used with this value, and the second parameter is defaulted.

    You can prevent such mistakes from creeping in by making the constructor explicit, which is gene­rally recommended for any constructor that can be called with one argument, unless you really want implicit conversions.

    To get your desired behaviour, you want direct initialization:

    Point p(a + r * xCoord, a + r * yCoord);