|
-
December 24th, 2002, 01:05 AM
#1
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 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;
}
-
December 24th, 2002, 01:29 AM
#2
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|