Q:

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

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ this Pointer (set 3).

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;
}

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;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

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.

Answer Program 2:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Structures | Find output programs | Set 1... >>
<< C++ this Pointer | Find output programs | Set 2...