Re: accessing subclass members via a base pointer?
On Wed, 31 Oct 2007 05:11:31 +0000, Tim H wrote:
I think you're stuck. Why not make a virtual SerializeIt() method
instead?
Serialization is not a problem and that part works. The problem is
that deserialization is pretty much useless if I still have to do
an explicit cast from a base pointer type back to the correct
subclass in the heirarchy upon object reconstruction.
struct base {
virtual base* getPtr()=0;};
struct subclass: public base {
subclass* getPtr() { return this; }
const char* isA() { return "subclass"; }
};
getPtr() is not virtual so it is statically bound based on the type,
which is known at compile time.
If you look closely you will see that getPtr() is declared virtual in the
base class and the correct sublcass::getPtr() is being called. I verified
this by inserting an exit(0) in subclass::getPtr().
Since p is a "base" and getPtr() is not virtual, I would expect the
compiler to generate a call to base::getPtr(). Since base doesn't have
an isA() method in this code, I'd expect it to fail. Does it actually
compile, or does your real code have a base::isA() method?
see above and note that the compiler error was in the OP...the virtual
nature of getPtr() has been verified but the compiler wont recognize the
subclass* return value of getPtr() to allow access to subclass::isA().
What I'm seeing is weird because the epxression p->getPtr() should return
a subclass* and that return type should be compatible with subclass::isA().