trouble with operator - (pointer)

Started by
4 comments, last by Falken42 16 years, 11 months ago
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?
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();

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

Yes, that indeed works, but it's not what I want. :)

I guess what I'm trying to do isn't possible?
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?
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

Stephen M. Webb
Professional Free Software Developer

Okay, makes sense now. :)

Thanks for the great explanation, Bregma!

This topic is closed to new replies.

Advertisement