Search code examples
c++classconstructorinitializationdefault-constructor

What is "{ x = a; y = b; }" doing in this incialization?


I am not sure about the exact purpose of this part of code and I need to explain it in my seminar.

class point {
public:
    point( int a = 0, int b = 0 ) **{ x = a; y = b; }**
    bool operator ==( const point& o ) { return o.x == x && o.y == y; }
    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
    int x, y;
};

Solution

  • { x = a; y = b; }
    

    is the compound statement of the constructor point( int a = 0, int b = 0 );

    Maybe it will be more clear if to rewrite the constructor like

    point( int a = 0, int b = 0 ) 
    { 
        x = a; 
        y = b; 
    }
    

    So the both parameters of the constructor have default argument equal to 0. The data members x and y are initialized (using the assignemnt operator) within the compound statement of the constructor.

    The constructor can be called like

    point p1; // x and y are initialized by 0
    point p2( 10 ); // x is initialized by 10 and y is initialized by the default argument 0
    point p3( 10, 20 ); // x is initialized by 10 and y is initialized by 20
    

    The same constructor can be defined also the following way

    point( int a = 0, int b = 0 ) : x( a ), y( b ) 
    { 
    }