Home » C++ programming language

Cascaded function call in C++ with example

Learn: What is cascaded function call in C++ programming language? How to call multiple functions in a single statement in C++?

Consider the following function calling

ob.FUN1().FUN2().FUN3();

Here, ob is the object name; FUN1, FUN2, and FUN3 are the member functions of the class and ob.FUN1().FUN2().FUN3(); the cascaded type of calling of the member functions.

C++ programming allows calling functions like this, when multiple functions called using a single object name in a single statement, it is known as cascaded function call in C++.

As we know that this pointer returns the pointer of current object, by using this pointer we can achieve cascaded function calls.

Consider the program:

#include<iostream>
using namespace std;

class Demo
{
	public:
		Demo FUN1()
		{
			cout <<"\nFUN1 CALLED"<<endl;

			return *this;
		}

		Demo FUN2()
		{
			cout <<"\nFUN2 CALLED"<<endl;

			return *this;
		}
		
		Demo FUN3()
		{
			cout <<"\nFUN3 CALLED"<<endl;

			return *this;
		}

};

int main()
{
	Demo ob;

	ob.FUN1().FUN2().FUN3();

	return 0;
}

Output

FUN1 CALLED

FUN2 CALLED

FUN3 CALLED

In this program, class Demo contains three member functions, each function is returning *this, which contains the reference of the object. If the function returns a reference of an object, then we can easily call the member function using reference of object the object.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.