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

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

Program 1:

#include <iostream>
using namespace std;

class Test {
    int VAL;

public:
    Test(int VAL)
    {
        this->VAL = VAL;
        cout << this->VAL;
    }
};

int main()
{
    Test T;

    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:17:10: error: no matching function for call to ‘Test::Test()’
     Test T;
          ^

Explanation:

The above code will generate an error, in the main() function we created the object class T. it will require a default or no-argument constructor which does not exist inside the class.

Program 2:

#include <iostream>
using namespace std;

class Test {
    int VAL;

public:
    Test(int VAL)
    {
        this->VAL = VAL;
        cout << this->VAL;
    }
};

int main()
{
    Test T(108);

    return 0;
}

Output:

108

Explanation:

Here, we created a class Test that contains a member VAL inside the class. And defined a parameterized constructor inside the class.

In the constructor, we passed an argument VAL, and VAL is also a data member of the class so that we used this pointer, which is used to access data members. Then we are accessing data member VAL using this pointer and local variable VAL can be used directly.

Then we are assigning value to the data member and print using cout.

Program 3:

#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(0);

    T3 = T1.Sum(T1, T2);

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

    return 0;
}

Output:

30 20 30

Explanation:

Here, we created a class called Test that contains a data member VAL, parameterized constructor, and member functions sum() and print()

sum() function is taking two objects of Test class as arguments and returning the current object using *this because this is a pointer to the current object and *this represents the current object.

In the main() function, we created three objects T1, T2, and T3 those are initialized with 10, 20, and 30 respectively.

We are calling the sum() function using T1 object and passing T1 and T2 as arguments, then the addition of the value of T1 and T2 assigned to T3, and T1 is also containing the sum of T1 and T2, because,

VAL = T1.VAL + T2.VAL;




Comments and Discussions!

Load comments ↻





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