• Advertisement
Sign in to follow this  

trouble with operator - (pointer)

This topic is 3947 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello all, Given the following code:
class A
{
public:
	void func();
};

class B
{
private:
	A *a;

public:
	A *operator ->()
	{
		return a;
	}
};


Trying to do:
B *b; b->func();
results in a compile error under VS2005 ('func' is not a member of 'B'), but:
B *b; (*b)->func();
works fine. Is there something I'm missing that will allow me to transparently access the members of class A from class B?

Share this post


Link to post
Share on other sites
Advertisement
You have a problem since you work with a pointer to B. So basically you'd need twice the -> operator (which i think is not possible).

Try this:

B b;

b->func();

Share this post


Link to post
Share on other sites
Quote:
Yes, that indeed works, but it's not what I want.
How about this?
b->operator->()->func();
:)

Seriously though, I think (*b)->func() is really what you're looking for. It seems your intent is to give B the semantics of a pointer type, in which case writing (*b)-> is both appropriate and idiomatic.

Or are we misunderstanding what you're trying to do?

Share this post


Link to post
Share on other sites
Quote:
Original post by bpoint
Is there something I'm missing that will allow me to transparently access the members of class A from class B?


There is nothing you can do. The static type of your variable b is B*. Dereferencing a B* does not yield a type with a function func().

There's a special rule for operator->() in which it will continue to be applied to its own result until a raw pointer is reached (the standard words it a little differently, but that's the intent and the end result). Problem is, here, that B* is already a raw pointer, so that rule doesn't apply.

As mentioned above, if you had a B object the rule would apply and your object would work like a smart pointer. As you have it now, you've got a dumb pointer to a smart pointer. No matter how you dress it up, you're never going to make a dumb pointer act smart.

So, either provide some sort of explicit accessor function, provide forwarding functions, or use your smart pointer class in a more idiomatic manner.

--smw

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement