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.


Related Tutorials

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.