Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic polymorphic pointers to base classes

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:

  1. Create the pointer at the time of instantiation, using a function that returns a base class pointer while actually allocating memory for the subclass instead, using the subclass's constructor. (Does such a creation function have a common name?)
  2. Casting an object using 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?

like image 810
johnbakers Avatar asked Apr 04 '13 13:04

johnbakers


1 Answers

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);
like image 196
Michael Kristofik Avatar answered Sep 29 '22 11:09

Michael Kristofik