Returning this from a Function - C++ Class

C++ examples for Class:this

Introduction

If the return type for a function member is a pointer to the class type, you can return this.

class Pool
{
private:
  double length;
  double width;
  double height;

public:
  // Constructors
  Pool(double lv = 1.0, double wv = 1.0, double hv = 1.0);

  double volume();                                  // Function to calculate the volume of a pool

  // Mutator functions
  Pool* setLength(double lv);
  Pool* setWidth(double wv);
  Pool* setHeight(double hv);
};

Pool* Pool::setLength(double lvalue)
{
  if(lv > 0) length = lv;
  return this;
}

Pool* Pool::setWidth(double wv)
{
  if(wv > 0) width = wv;
  return this;
}

Pool* Pool::setHeight(double hv)
{
  if(hv > 0) height = hv;
  return this;
}

Pool aPool {10.0,15.0,25.0};                                 // Create a pool
aPool.setLength(20.0)->setWidth(40.0)->setHeight(10.0);     // Set all dimensions of aPool

Related Tutorials