views:

206

answers:

5

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

A: 

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.

Kotti
A: 

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

Tapdingo
By default, class O does not have a -> operator that returns an O*.
Didier Trosset
A: 

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

zooropa
+2  A: 

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;
}
Eddy Pronk
what happens if the func() of S was declared as such:virtual void func() = 0;
hero
virtual functions should at least be protected, but preferably private. It is the responsibility of class S to make sure ses is pointing to a valid object.
Eddy Pronk
virtual private functions? Unless you're full of friend class declarations, I think private and virtual are mostly mutually exclusive.
luiscubal
@luiscubal: Actually having private virtual is a good technique (used extensively in the streaming libraries). But it is not always appropriate If you just want a class to override a pure virtual method that there is no need to make it private, but if you want the base class to do some work before the virtual call then it is usefull. Saying it should be protected or private is going to far that is just a technique that can be used.
Martin York
@Martin York: I see there are already questions about this topic(virtual private) on stack overflow. I'll have to investigate this weird topic.
luiscubal
If the function S is virtual, then you will get a virtual function lookup. The behaviour of this operator is literally as if the instance of O was actually an S*.
DeadMG
+11  A: 

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.

sharptooth
"With suce overload" => Did you meant "such" or is "suce" the name of the `->` operator ? (non native-english speaker asking)
ereOn
@ereOn: Fixed, that were typos.
sharptooth