The World of Mayukh Bose

<< Back to Main Page Mayukh's world: e-mail me | about
Mayukh's World: Operator Overloading With C++ Thursday, November 23, 2017
Index
  • Introduction
  • What Operators?
  • Rules
  • Assignment Operator
  • More on Assignment
  • Arithmetic Operators
  • Arithmetic with Globals
  • Increment/Decrement
  • Operator-Assignment
  • Unary Operators
  • Relational Operators
  • Bitshift/Extraction
  • Subscript Operator
  • Function Call Operator
  • Bit and Logical Ops
  • Comma Operator
  • Pointer to Member
  • new and delete Ops
  • Credits and Thanks
  • My Free Software
  • Delphi/C++ Builder
  • Pocket PC
  • FreeSpeech Chat
  • C/C++ Freebies
  • Perl
  • Python
  • Ruby
  • C++ Operator Overloading Tutorial e-mail me

    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.


    <<Previous: Comma Operator ^Up to Mayukh's World^ Next: new and delete Operators >>

    Copyright © 2004 Mayukh Bose. All rights reserved.
    This work may be freely reproduced provided this copyright notice is preserved.
    OPTIONAL: Please consider linking to this website (http://www.mayukhbose.com/) as well.