I saw this code but I couldn't understand what it does:
inline S* O::operator->() const
{
return ses; //ses is a private member of Type S*
}
so what happens now if I used ->
?
I saw this code but I couldn't understand what it does:
inline S* O::operator->() const
{
return ses; //ses is a private member of Type S*
}
so what happens now if I used ->
?
It's an overloaded operator that would return a pointer to some member of type S
.
Like, if you write
O object;
(object->)...
the part (object->)
would become your pointer.
It overloads the operator -> of the class O, that returns now an S* instead of an O*
Anytime an object of type O uses the -> operator a pointer to ses will be returned.
Is you have an instance of class O and you do
obj->func()
then the operator-> returns ses and then it uses the returned pointer to call func().
Full example:
struct S
{
void func() {}
};
class O
{
public:
inline S* operator->() const;
private:
S* ses;
};
inline S* O::operator->() const
{
return ses;
}
int main()
{
O object;
object->func();
return 0;
}
Now if you have
O object;
object->whatever()
first the overloaded operator->
will be called, which will return ses
stored inside the object, then operator->
(built-in in case of S*
) will be called again for the returned pointer.
So
object->whatever();
is equivalent to pseudocode:
object.ses->whatever();
the latter would be of course impossible since O::ses
is private
- that's why I call it pseudocode.
With such overload you can create a wrapper around a pointer - such wrapper is typically called smart pointer.