operator overloading fails

hello all

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:
	void operator->()
	{
		cout<<"in operator \n";
	}
	void fun()
	{
		cout<<"here in function \n";
	}
};

int main()
{
test * t = new test;
t->fun();
return 0;
}


output : here in function
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";
    return this;
}

Then you can
1
2
test t;
t->fun();


But this is not how operator->() traditionally work.

thanks R0mai , but how code written by me behaves ? why it didn't go in

overloaded operator function block ?.
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.

1Assuming it is a structure or class pointer
Last edited on

thanks R0mai. it really helps.
Topic archived. No new replies allowed.