Polymorphic type?

As I was reading the Type Casting section of the C++ guide, I became confused in the dynamic_cast section.

In this example:
1
2
3
4
5
6
7
8
class CBase { };
class CDerived: public CBase { };

CBase b; CBase* pb;
CDerived d; CDerived* pd;

pb = dynamic_cast<CBase*>(&d);     // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b);  // wrong: base-to-derived 

Everything seems to make sense, however... I did become confused when the guide stated that the CBase class was NOT polymorphic. I plugged it into the compiler and sure enough it said it was not a polymorphic type.

Now, long story short, why is:
class CBase { virtual void dummy() {} };
Deemed polymorphic and:
class CBase { };
Not polymorphic?
(Both of which DO have a derived class.)

I'm still stuck a bit in Java mode when it comes to inheritance and polymorphism. So as far as my brain is telling me, the non-polymorphic CBase could still potentially be made to point at its derived class. Would that not be polymorphic?

Thanks for any assistance!
I plugged it into the compiler and sure enough it said it was not a polymorphic type.
Huh? What do you mean?

It's not enough for a class to have derived classes to be called polymorphic. The requirement is to have at least one method that can be overridden (i.e. at least one virtual method).

the non-polymorphic CBase could still potentially be made to point at its derived class. Would that not be polymorphic?
That's true, but the point of polymorphism is being able to call different code based on the type of the object without modifying code at the calling point. If a function doesn't let you do that, then it's not polymorphic.
Suppose both CBase and CDerived each have a non-virtual method dummy(). Here:
1
2
3
4
CDerived cd;
cd.dummy();
CBase *cb=(CBase *)&cd;
cb->dummy();
Here, both calls call the same method (CBase::dummy()), because, since CBase::dummy() wasn't virtual, CDerived wasn't able to override it. If CBase::dummy() was virtual, the first call would have called CBase::dummy(), while the second one would have called CDerived::dummy().
Last edited on
I plugged it into the compiler and sure enough it said it was not a polymorphic type.
Huh? What do you mean?


What I meant was that I created a program that did exactly what the first example did and my C++ compiler stated that the operand for a run time call of dynamic_cast required a polymorphic class type, which CBase in that example is not.

You're excellent at answering questions and I appreciate the help a lot!
Topic archived. No new replies allowed.