×

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

C++ this Pointer | Find output programs | Set 3

This section contains the C++ find output programs with their explanations on C++ this Pointer (set 3).
Submitted by Nidhi, on June 17, 2020

Program 1:

#include <iostream>
using namespace std;

class Test {
    int VAL;

public:
    Test(int v)
    {
        VAL = v;
    }
    Test* Sum(Test T1, Test T2)
    {
        VAL = T1.VAL + T2.VAL;

        return this;
    }
    void print()
    {
        cout << VAL << " ";
    }
};

int main()
{
    Test T1(10);
    Test T2(20);

    Test* T3;

    T3 = T1.Sum(T1, T2);

    T1.print();
    T2.print();
    T3->print();

    return 0;
}

Output:

30 20 30

Explanation:

Consider the sum() function, the function is taking two objects of Test class arguments and returning the pointer of the current object using this

And, in the main() function, we created two objects T1, T2, and a pointer T3, which is holding the current object pointer returned by sum(). The sum() is adding the values of T1 and T2 and assigning in T1 because we are calling the function sum() using T1 and returning the address of T1 which is assigning to the pointer T3.

Program 2:

#include <iostream>
using namespace std;

class Test {
public:
    Test call1()
    {
        cout << "call1 ";
        return *this;
    }
    Test call2()
    {
        cout << "call2 ";
        return *this;
    }
    Test call3()
    {
        cout << "call3 ";
        return *this;
    }
};

int main()
{
    Test T1;

    T1.call1().call2().call3();

    return 0;
}

Output:

call1 call2 call3

Explanation:

Here, we implemented a cascaded function call using this pointer, and created the class Test with 3 member functions call1(), call2(), and call3(). All these functions will return the current object of the class using *this.





Comments and Discussions!

Load comments ↻





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