C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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.









COMMENTS