Cascading Member Functions in C++

In this tutorial, we will learn cascading member functions in C++. Suppose there is a class Square with member functions area() and perimeter() that print area and perimeter of the square for a given side.

Normally, what we do is call these functions in separate statements for a created instance of the class and print the output but there is a better method. We can use cascading and call both the function for an object in a single statement. Let’s see how we can do this with examples.

Let’s say sq is an object of the class Square. Now to print the area and perimeter respectively, we call these methods on the object sq like this.

sq.area();
sq.perimeter();

Using cascading we can do the same but in a single statement as shown below.

sq.area().perimeter();

See the code for a better understanding.

#include <iostream>

using namespace std;

class Square
{
  public:
    int side;
    
    //functions
    Square area()
    {
      cout << "Area of the square is :" << side*side <<endl;
      return *this;
    }
    Square perimeter()
    {
      cout << "Perimeter of the square is :" << 4*side <<endl;
      return *this;
    }
};

int main()
{
  Square sq;
  
  sq.side =3;
  
  //cascading function calls
  sq.area().perimeter();
  
  return 0;
}

The output of the program is:

 Area of the square is :9
Perimeter of the square is :12

As you can see, we have created a class Square and defined functions area() and perimeter() for it. The function area() prints the area of the square and the function perimeter() prints the perimeter of the square. *this pointer specifies that the functions return a reference to the object which makes cascading possible.

I hope, you got a clear idea of cascading member function in C++.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *