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

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

Program 1:

#include <iostream>
using namespace std;

int main()
{
    int A = 10;
    this* ptr;

    ptr = &A;

    *ptr = 0;

    cout << *ptr << endl;

    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:7:5: error: invalid use of ‘this’ in non-member function
     this* ptr;
     ^~~~
main.cpp:7:11: error: ‘ptr’ was not declared in this scope
     this* ptr;
           ^~~

Explanation:

The code will generate an error because we cannot use this pointer outside the class. because this pointer points to the current object inside the class.

Program 2:

#include <iostream>
using namespace std;

class Test {
    int T1;

public:
    Test()
    {
        this* ptr;

        *ptr = &T1;

        cout << *ptr;
    }
};

int main()
{
    Test T;

    return 0;
}

Output:

main.cpp: In constructor ‘Test::Test()’:
main.cpp:10:15: error: ‘ptr’ was not declared in this scope
         this* ptr;
               ^~~

Explanation:

The above code will generate an error because this is the default pointer of the current object we can access members of the class inside the class. But we cannot create pointers using this.

In the above program, we created pointers using this inside the constructor, which is not correct.

Program 3:

#include <iostream>
using namespace std;

class Test {
    int T1;

public:
    Test()
    {
        T1 = 10;
        cout << this->T1;
    }
};

int main()
{
    Test T;

    return 0;
}

Output:

10

Explanation:

Here, we created a class Test that contains data member T1 and we defined a default constructor inside the class Test.

In the constructor, we assign value 10 to the T1 and print using the below statement.

cout<<this->T1;

In the above statement, we accessed T1 using this, because the this is a pointer to the current object. Thus, it will print 10 on the console screen.





Comments and Discussions!

Load comments ↻





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