-5

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Souradeep
  • 31
  • 1
  • 3

4 Answers4

2

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Below one is the constructor(constructor means class name and member function name should be same & it should not have any return type)

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

setX and setY are normal member functions of the class not the constructor's as just their return types are class-name doesn't make them constructor.

Secondly, If setX and setY were constructor then you don't have to call like obj1.setX(10).setY(20); as constructors gets called automatically whenever objects gets created.

Achal
  • 11,821
  • 2
  • 15
  • 37
0

Constructors have the name of the class as the method name.

What you have are called setters.

Most setters return void.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

No, they are not constructors.

The methods that return 'this' can be chained together, one after the other.

E.g `a.setX (1).setY (2);

Where a is an instance of Test

Dragonthoughts
  • 2,180
  • 8
  • 25
  • 28