Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading -> operator in c++

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 ->?

like image 670
hero Avatar asked May 25 '10 11:05

hero


People also ask

Can we overload -> operator?

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.

How does -> operator overload work?

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.

What is operator overloading with example in C?

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.

Can we overload arrow operator in C++?

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 .


1 Answers

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.

like image 63
sharptooth Avatar answered Sep 28 '22 06:09

sharptooth