Reputation: 83
class A
{
public:
A* operator->() const
{
}
void Test() {}
};
then call it like this.
A* a = new A;
a->Test();
The code builds and runs successfully in VC2010. It seems very strange. I am wondering it is by design or it is a bug of VC2010?
Thanks
Upvotes: 2
Views: 117
Reputation: 39294
Your code is:
A* a = new A;
a->Test();
The "a" is a pointer to an A. It is NOT an A object itself, it is a memory address of the A object on the heap.
When you call a->Test()
you invoke the pointer's -> operator (built in for all pointer types in C++). You would have to do this to invoke your operator:
//Create an A (NOT a pointer).
A a;
//Invoke the A's operator ->
a->Test();
Which is how STL iterators work - they're class types, not pointers to class types. Note that the return type of operator -> must make sense for the operation/member you're trying to invoke.
So, here's an example that would call test via the ->:
#include <iostream>
class A
{
public:
A* operator->()
{
return this;
}
void Test() { std::cout << "Hello World!"; }
};
int main()
{
A a;
a->Test();
}
It's strange, but it works because a->Test();
returns the current object, which Test()
is then called on (see the return this;
line).
See STL iterators for useful examples of why you'd actually want to do this.
Upvotes: 1
Reputation: 28178
You aren't calling your operator->
in your example, you are calling Test
directly from an A*
. You want:
(*a)->Test();
Or...
A a;
a->Test();
There's nothing wrong with VS2010 concerning operator->
(that I know of).
Using ->
on a pointer named a
effectively executes: (*a).
. Using ->
on a variable by value will invoke your operator->
if present, or be a syntax error if there is no operator->
.
Upvotes: 3