I know that the assignment operator can be overloaded. When writing to an object, the object's overload function is called.
Obj = 10; // Obj's assignment overload function called.
Is there a way to define a function to be called when an object is read?
int a = Obj;
In this case Obj
's reading function would be called and the return value would be assigned to a
.
CodePudding user response:
You're looking for what's sometimes called a cast operator.
example:
#include <iostream>
struct example
{
int val;
operator int() const { return val; }
};
int main ()
{
example x{42};
int y = x;
std::cout << y;
}
Will print 42.