hero
hero

Reputation: 103

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

Upvotes: 5

Views: 492

Answers (5)

Eddy Pronk
Eddy Pronk

Reputation: 6695

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;
}

Upvotes: 2

sharptooth
sharptooth

Reputation: 170469

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.

Upvotes: 11

Paul Kelly
Paul Kelly

Reputation: 4019

Anytime an object of type O uses the -> operator a pointer to ses will be returned.

Upvotes: 0

Tapdingo
Tapdingo

Reputation: 259

It overloads the operator -> of the class O, that returns now an S* instead of an O*

Upvotes: -1

M. Williams
M. Williams

Reputation: 4985

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.

Upvotes: 0

Related Questions