0

operator*() c++

hello people who can explain me this row in this code? why is int by reference? int& operator*() { return *data; } #include <iostream> using namespace std; class MyInt { public: explicit MyInt(int* p = nullptr) { data = p; } ~MyInt() { delete data; } int& operator*() { return *data; } private: int* data; }; int main() { int* p = new int(10); MyInt myint = MyInt(p); cout << *myint << endl; return 0; }

17th Feb 2020, 6:35 PM
Lilit
Lilit - avatar
1 Answer
+ 1
It's because you can do : *myint = 3; Here, thanks to reference, you can change the value of myint.
17th Feb 2020, 6:43 PM
Théophile
Théophile - avatar