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
6 Respuestas
+ 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
+ 1
Thanks $¢𝐎₹𝔭!𝐨𝓝 it was a good explanation along with solution.
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.
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;
}
0
This code works , you dont need * with "*this" this cause error 🙂
- 1
Please show your code here.