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:
- 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?)
- 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?