Learn C++ - C++ this Pointer






The this pointer contains the address of current object.

When you call the function for a different object, this will contain the address of that object.

Returning this from a Function

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

You can then use the pointer returned by one function member to call another.

class Box 
{ 
private: 
  double length; 
  double width; 
  double height; 
  
public: 
  // Constructors 
  Box(double lv = 1.0, double wv = 1.0, double hv = 1.0); 
  
  double volume();                                  // Function to calculate the volume of a box 
  
  // Mutator functions 
  Box* setLength(double lv); 
  Box* setWidth(double wv); 
  Box* setHeight(double hv); 
}; 
Box* Box::setLength(double lvalue) 
{ 
  if(lv > 0) length = lv; 
  return this; 
} 
  
Box* Box::setWidth(double wv) 
{ 
  if(wv > 0) width = wv; 
  return this; 
} 
  
Box* Box::setHeight(double hv) 
{ 
  if(hv > 0) height = hv; 
  return this; 
} 
 
Box aBox {10.0,15.0,25.0};                                 // Create a box 
aBox.setLength(20.0)->setWidth(40.0)->setHeight(10.0);     // Set all dimensions of aBox