Can we dereference this pointer in c++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can we dereference this pointer in c++?

#include <iostream> using namespace std; class Base { public : Base() { cout<<this<<endl; this->num = 5; cout<<this->num<<endl; cout<<*this<<endl; } int num; }; int main() { Base obj; cout<<&obj<<endl; return 0; } //This gives error. Can anyone help me in understanding the cause

11th Jun 2020, 5:42 PM
Nilesh
Nilesh - avatar
6 Answers
+ 2
First the thing is you can dereference the this pointer. When you do it it will return reference of the object. You can not print reference of object directly using cout. To use cout with the object you have to overload the << operator. Below is the code for your reference to overload the operator and then it will works correctly. https://code.sololearn.com/c795rjeG48Xi/?ref=app
11th Jun 2020, 7:11 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
Thanks $¢𝐎₹𝔭!𝐨𝓝 it was a good explanation along with solution.
12th Jun 2020, 3:13 AM
Nilesh
Nilesh - avatar
0
#include <iostream> using namespace std; class Base { public : Base() { cout<<this<<endl; this->num = 5; cout<<this->num<<endl; cout<<*this<<endl; } int num; }; int main() { Base obj; cout<<&obj<<endl; return 0; } Above is the code. I was just playing with this pointer and stuck with compilation error.
11th Jun 2020, 6:28 PM
Nilesh
Nilesh - avatar
0
#include <iostream> using namespace std; class Base { public : Base() { cout<<this<<endl; this->num = 5; cout<<this->num<<endl; cout<<this<<endl; } int num; }; int main() { Base obj; cout<<&obj<<endl; return 0; }
11th Jun 2020, 7:02 PM
꧁༒☬Bad☬Boy☬༒꧂
꧁༒☬Bad☬Boy☬༒꧂ - avatar
0
This code works , you dont need * with "*this" this cause error 🙂
11th Jun 2020, 7:03 PM
꧁༒☬Bad☬Boy☬༒꧂
꧁༒☬Bad☬Boy☬༒꧂ - avatar
- 1
Please show your code here.
11th Jun 2020, 5:54 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar