Q:

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

belongs to collection: C++ find output programs

0

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

Program 1:

#include <iostream>
using namespace std;

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

    ptr = &A;

    *ptr = 0;

    cout << *ptr << endl;

    return 0;
}

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

Program 3:

#include <iostream>
using namespace std;

class Test {
    int T1;

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

int main()
{
    Test T;

    return 0;
}

All Answers

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

Answer Program 1:

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.

Answer Program 2:

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.

Answer Program 3:

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.

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++ this Pointer | Find output programs | Set 2... >>
<< C++ Constructor and Destructor | Find output progr...