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