×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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++?

Cascaded function call in C++

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 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.

Example of cascaded function call in C++

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

Explanation

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.

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.