CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 1999
    Location
    Mumbai, India
    Posts
    207

    Post Overloading the '->'(member access) operator

    Hi,

    In the following code I am overloading the member
    access operator '->' . But when I actually make a
    member function call using '->', the message inside
    the overloaded function does not show. The method
    call works alright as if the operator was never
    overloaded.

    PHP Code:
    #include <iostream.h>
    #include <string>

    // ComplexNumber: class definition
    class ComplexNumber
    {
    private:
        
    long X;
        
    long Y;
        
    public:
        
    void Assign(long pXlong pY)
        {
            
    pX;
            
    pY;
        }

        
    void Show(void)
        {
            
    cout << << "+" << <<"i" << endl;
        }

        
    ComplexNumberoperator->(void)
        {
            
    cout << "Overloaded -> ..." << endl;
            return 
    this;        
        }
    };

    // main()
    int main(int argccharargv[])
    {
        
    ComplexNumber *pC1 = new ComplexNumber;

        
    pC1->Assign(810);
        
    pC1->Show();

        
    delete pC1;

        return 
    0;

    Thank you.
    Sayan
    ====================

    Sayan Mukherjee
    [Email: [email protected]]

  2. #2
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125
    Of course,

    You overloaded the operator -> for an OBJECT of type ComplexNumber.

    Then you wrote code that used a POINTER to a Complex Number.

    For fun, put the following in your test code and step into it.

    Code:
    ComplexNumber x;
    x->Assign(1,2);
    The above is NOT a syntax error, you defined a dereferencing operator for an object. This is typically considered "bizarre" behaviour. The same as

    Code:
    int operator +(SomeClass const &rhs)
    {
       return m_value - rhs.m_value;
    }
    Of course the place where you WOULD want to implement the "->" operator is if you are implementing an object THAT SHOULD ACT LIKE A POINTER.

    Do a search on "Smart Pointers" "auto_ptr" and the like for more information.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured