5

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?

David G
  • 94,763
  • 41
  • 167
  • 253
johnbakers
  • 24,158
  • 24
  • 130
  • 258

1 Answers1

9

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);
Michael Kristofik
  • 34,290
  • 15
  • 75
  • 125
  • indeed, I was just coincidentally looking up a word in the dictionary, the word was *elegant* and I did a double-take when the definition was in fact the exact code snippet you provided above! – johnbakers Apr 04 '13 at 13:31
  • +1 for pointing out that dynamic allocation & pointers are orthogonal to polymorphism (even if often used together). – Matthieu M. Apr 04 '13 at 14:28