Sign in to follow this  
bpoint

trouble with operator - (pointer)

Recommended Posts

bpoint    464
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
jyk    2094
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
Bregma    9214
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this