Class Member Access Operator Overloading
# C++ Class Member Access Operator -> Overloading
[ C++ Overloading Operators and Functions](#)
The class member access operator (->) can be overloaded, but it is a bit tricky. It is defined to give a class "pointer" behavior. The operator -> must be a member function. If the -> operator is used, the return type must be a pointer or an object of a class.
The operator -> is typically used in conjunction with the dereference operator * to implement "smart pointer" functionality. These pointers are objects that behave similarly to normal pointers, with the only difference being that when you access an object through the pointer, they perform additional tasks. For example, automatically deleting the object when the pointer is destroyed or when the pointer points to another object.
The dereference operator -> can be defined as a unary postfix operator. That is, given a class:
class Ptr{ //... X * operator->();};
An object of class **Ptr** can be used to access members of class **X** in a way very similar to pointer usage. For example:
void f(Ptr p ){ p->m = 10 ; // (p.operator->())->m = 10}
The statement p->m is interpreted as (p.operator->())->m. Similarly, the following example demonstrates how to overload the class member access operator ->.
## Example
#include#includeusing namespace std; // Assume an actual class class Obj{static int i, j; public: void f()const{cout<<i++ <<endl; }void g()const{cout<<j++ <<endl; }}; // Static member definition int Obj::i = 10; int Obj::j = 12; // Implement a container for the above class class ObjContainer{vectora; public: void add(Obj* obj){a.push_back(obj); // Call vector's standard method}friend class Sma
YouTip