Re: Inheritance Issue
Al wrote:
I have been dealing with an issue that has cropped up several times
and I'm not sure what the best approach is. In its simplest form, the
problem is:
class Base { ... };
class Derived : public Base { public: int Field; };
Now, somewhere else I have:
void foo(Base* base) {
// if (base is Derived)
// do something with Field.
This is an utterly bad specification. Your design seems to be
based on a very bad premise: that 'foo' needs to know about the
contents of a derived class while actually working with a pointer
to the base class.
}
So I see two ways of dealing with this. One is a straightforward
downcast:
void foo(Base* base) {
if (Derived* derived = dynamic_cast<Derived*>(base))
std::cout << derived->Field;
}
Now, I dislike downcasts and avoid them as much as possible. So
another approach is to change the classes to something like:
class Base { public: boost::optional<int> Field; };
class Derived : public Base { ... };
That way, I can do the slightly cleaner:
void foo(Base* base) {
if (base->Field)
std::cout << *base->Field;
}
I realize that this doesn't really fix the problem, but the syntax is
a little nicer :). Anyway, between these two, which seems better? Are
there other approaches?
Yes. If your 'foo' function needs to do something with 'Field' in
'Base', 'Base' should have the 'Field'.
If 'foo' doesn't care about 'Field' but should instruct 'Base' to do
something special (that might affect 'Field'), it should be a virtual
function in 'Base' that does nothing itself, but allows 'Derived' to
do what is needed.
Is this just a generic multiple-dispatch scenario?
Of course not. It's a generic polymorphic behaviour.
IOW, redesign.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]