Search code examples
c++declarationconstruct

Is this a constructor (C++)


I saw this code on internet today:

#include<iostream>
using namespace std;

class Test
{
private:
  int x;
  int y;
public:
  Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
  Test setX(int a) { x = a; return *this; }
  Test setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
  Test obj1;
  obj1.setX(10).setY(20);
  obj1.print();
  return 0;
}

Here see these lines:

Test setX(int a) { x = a; return *this; }
Test setY(int b) { y = b; return *this; }

Are setX and setY constructors? If not, what are they? Any help will be appreciated.


Solution

  • The class has only one constructor

    Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
    

    that is the default constructor because it can be called withoit arguments..

    The constructor name is the same as the class.name.

    So these

      Test setX(int a) { x = a; return *this; }
      Test setY(int b) { y = b; return *this; }
    

    are two non-static member functions named setX and setY that have one argument of the type int and the return type Test. The functions return copies of the object for which the functions are applied.

    So for example this statement

    obj1.setX(10).setY(20);
    

    does not make sense because the call setY is applied to the temporary object returned by the call objq.setX( 10 ).

    The methods should be declared at least like

      Test & setX(int a) { x = a; return *this; }
      Test & setY(int b) { y = b; return *this; }
    

    If the functions have the return type Test then this statement

      obj1.setX(10).setY(20);
      obj1.print();
    

    produce output

    x = 10 y = 0
    

    If to declare the functions with the return type Test & then the output of the above statements will be

    x = 10 y = 20