Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call "operator->()" directly?

Tags:

c++

For some strange reason, I need to call the operator->() method directly. For example:

class A {
    public:
        void foo() { printf("Foo"); }
};

class ARef {
    public:
        A* operator->() { return a; }
    protected:
        A* a;
}; 

If I have an ARef object, I can call foo() by writing:

aref->foo();

However, I want to get the pointer to the protected member 'a'. How can I do this?

like image 249
Anne Nonimus Avatar asked Aug 03 '10 16:08

Anne Nonimus


2 Answers

aref.operator->(); // Returns A*

Note that this syntax works for all other operators as well:

// Assuming A overloads these operators
A* aref1 = // ...
A* aref2 = // ...
aref1.operator*();
aref1.operator==(aref2);
// ...

For a cleaner syntax, you can a implement a Get() function or overload the * operator to allow for &*aref as suggested by James McNellis.

like image 65
In silico Avatar answered Sep 29 '22 18:09

In silico


You can call the operator directly using the following syntax:

aref.operator->()

You should probably overload both -> and *, so that usage is consistent with the usage of a pointer:

class ARef {
    public:
        A* operator->() { return a; }
        A& operator*() { return *a; }
    protected:
        A* a;
}; 

Then you can use the following to get the pointer value:

&*aref

You can also implement a get() member function that returns the A* directly, which is much, much cleaner than either of these solutions (most smart pointer classes provide a get() member function).

like image 32
James McNellis Avatar answered Sep 29 '22 18:09

James McNellis