In article <jY*********************@fe05.news.easynews.com> ,
sc***@nospam.com says...
Hi All,
Am I correct in assuming that there is no way to have a base pointer to an
object that uses multiple inheritance?
No.
For example,
[ code elided ... ]
Is there a way to define a pointer that will allow access to objects of
either C or D with a dynamic_cast?
I'm not sure I follow. A pointer to a base class can point to an object
of a derived class (any class derived from that base). The derived class
may have other base classes as well, without affecting this -- and no
dynamic_cast is needed for this. A pointer to a derived class can be
converted to a pointer to a (public) base class implicitly.
You use dyamic_cast to conversions on the opposite direction, starting
with a pointer to a base, and converting to a pointer to the derived
class. Again, multiple inheritance doesn't really affect much -- you can
have a pointer to any base class, and as long as the object really is of
the desired destination class, dynamic_cast can convert it successfully:
#include <iostream>
// switched to stucts since everything's public anyway.
struct A {
virtual void f() {std::cout << "A::f()\n"; }
};
struct B {
virtual void g() {std::cout<< "B::g()\n"; }
};
struct C : A, B {
virtual void f() { std::cout << "C::f()\n"; }
virtual void g() { std::cout << "C::g()\n"; }
void h() { std::cout << "h (unique to C)\n"; }
};
struct D : A, B {
virtual void f() { std::cout << "D::f()\n"; }
virtual void g() { std::cout << "D::g()\n"; }
void e() { std::cout << "e (unique to D)\n"; }
};
int main() {
// pointers to base classes pointing at objects of derived classes
A *a = new C;
B *b = new D;
// use the virtual functions.
a->f();
b->g();
// convert to pointers to derived objects
C *c = dynamic_cast<C*>(a);
D *d = dynamic_cast<D*>(b);
// conversions should have succeeded.
assert(c!=NULL);
assert(d!=NULL);
// invoke functions unique to derived classes.
c->h();
d->e();
// implicitly convert back to base class pointers. Note
// we've swapped the two this time.
a = d;
b = c;
// invoke virtual functions again. Note the changed output.
a->f();
b->g();
return 0;
}
--
Later,
Jerry.
The universe is a figment of its own imagination.