here operator overloading of -> operator fails , why ?
any idea ? , thanks in advance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class test
{
public:
voidoperator->()
{
cout<<"in operator \n";
}
void fun()
{
cout<<"here in function \n";
}
};
int main()
{
test * t = new test;
t->fun();
return 0;
}
This is not how operator->() works. To have the desired output with this class declaration your main should look like this:
1 2 3 4 5 6 7
int main()
{
test t;
t.operator->();
t.fun();
return 0;
}
In your original code you call test*::operator->(), which you can't overload. To make operator->() work correctly it should return a pointer. For example :
1 2 3 4 5
test *operator->()
{
cout<<"in operator \n";
returnthis;
}
Then you can
1 2
test t;
t->fun();
But this is not how operator->() traditionally work.
why it didn't go in overloaded operator function block ?.
Because you've never called it. As I've said you called operator->() on a pointer, and not an object. -> will always behave the same way on every type of pointer1. http://cplusplus.com/doc/tutorial/structures/#arrow
see the table.
You can only have an overloaded version of -> if it gets called on an object.