Click to See Complete Forum and Search --> : Overloading the '->'(member access) operator


Sayan Mukherjee
December 24th, 2002, 12:05 AM
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.


#include <iostream.h>
#include <string>

// ComplexNumber: class definition
class ComplexNumber
{
private:
long X;
long Y;

public:
void Assign(long pX, long pY)
{
X = pX;
Y = pY;
}

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

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

// main()
int main(int argc, char* argv[])
{
ComplexNumber *pC1 = new ComplexNumber;

pC1->Assign(8, 10);
pC1->Show();

delete pC1;

return 0;
}

TheCPUWizard
December 24th, 2002, 12:29 AM
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.


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


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.