|
Pointer to Member Operator ->
The C++ pointer to member operator is ->. Per the latest C++ standards, this is treated as a
Unary operator. This means, you cannot declare the overloaded function
as a global function or a non-static member function. Since we've already studied how to overload
unary operators, we will not repeat that information here.
One use for this operator overload is for smart pointer classes. Let us consider that we have an
object called SomeClass that has a method called DoSomething().
class SomeClass {
public:
void DoSomething();
};
Now we can wrap a SomeClass pointer inside another class called SmartClass like this:
class SmartClass {
private:
SomeClass *ptr;
public:
SmartClass() { ptr = NULL; }
void Init() { /* Do something to initialize ptr properly */ }
SomeClass* operator->(void);
};
SomeClass* SmartClass::operator->(void) {
if (ptr)
return ptr;
else {
LogError(); // Log an error
throw Exception();
}
}
Now, if we have code like this:
SmartClass sc;
...
sc->DoSomething();
If sc has been initialized properly, then the -> operator will return a SomeClass object
pointer, which can then call the DoSomething() method. If sc hasn't been initialized properly, then the -> overloaded
function will log an error and throw an exception. This prevents the code from using a NULL pointer by accident.
|
|