While I've been working in c++ for a while, I haven't had need to use polymorphic features until now, and I'm very intrigued by them.
If I have a base class ClassA
and another ClassB
derives from it, I understand that I can have virtual
member function in ClassA
that, when implemented in ClassB
, will be called in a ClassB
instance even if that instance is pointed at using a ClassA
pointer. Without this virtual
keyword, I presume the base class implementation would prevail when using a base class pointer, yet be operating on an object that was instantiated from the subclass, which seems questionable to me if in fact ClassB
has its own implementation of the same function that is effectively ignored in such a case.
Is this a correct understanding of polymorphic behavior?
Now the real question is how do you refer to ClassB
using a pointer to is base class. I can really only think of two ways:
static_cast
and assigning it to a pointer to the base class.Are these the two main techniques for generating base class pointers to objects of a subclass?
The easiest way is to simply assign it, no cast necessary:
ClassA *ptrA = new ClassB;
You're correct that you need the virtual
keyword to enable polymorphic behavior. Here's one way to think about it. C++ operates on the static type of an object. When you call ptrA->foo()
, the type of the pointer is ClassA*
. If that function is not declared virtual
, then it will blindly call ClassA
's version of the function. There's no other choice. But if foo()
is virtual
, then it knows to stop and ask, "Wait, what type am I really?" And the answer in that case is ClassB
, so it will call ClassB
's version.
Also note that you don't need pointers to achieve this. Another common way you'll see polymorphism in action is via a function call:
void bar(ClassA &aObj)
{
aObj.foo();
}
// ...
ClassB bObj;
bar(bObj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With