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 ->
?
These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator.
The operator-> has special semantics in the language in that, when overloaded, it reapplies itself to the result. While the rest of the operators are applied only once, operator-> will be applied by the compiler as many times as needed to get to a raw pointer and once more to access the memory referred by that pointer.
Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.
Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof , which is technically an operator). C++ adds a few of its own operators, most of which can be overloaded except :: and .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With