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;
}
Answer Program 1:
Output:
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:
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:
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.
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