Artifact [d728de4e0f]
Not logged in

Artifact d728de4e0fa5483a6c520ff7887c8a4a57f812cd:

Wiki page [Virtual base methods] by Les Farrell 2013-01-17 21:53:43.
D 2013-01-17T21:53:43.371
L Virtual\sbase\smethods
P 2e1a31dec2474056d10f6f2bc3dcaa819b11ba36
U Les\sFarrell
W 2128
<p>The three cornerstones of Object-Oriented Programming are encapsulation,
inheritance and polymorphism. Previous examples have demonstrated how data can
be encapsulated within a C++ class and how derived classes inherit the
properties of their base class. This chapter introduces the final cornerstone
principle of polymorphism.</p>

<p>The term 'Polymorphism' (from the Greek meaning 'many forms') describes the
ability to assign a different meaning, or purpose, to an entity according to
its context.</p>

<p>In C++, overloaded operators can be described as polymorphic. For instance,
the * character can represent either the multiply operator or the dereference
operator according to its context. More importantly, C++ has the ability to
bind specific derived class objects to base class pointers to create
polymorphic methods.</p>

<p>The key to creating a polymorphic method is to first declare a 'virtual'
base class method - this is just a regular declaration preceded by the virtual
keyword. The declaration of a virtual method indicates that the class will be
used as a base class from which another class will be derived. This derived
class will contain a method to override the virtual base method.</p>

<p>A pointer to the base class can be assigned an object of the derived class.
This pointer can be used to access regular methods of the base class and
overriding methods of the derived class. For instance, this statement assigns a
new <b>Pigeon </b>class object (derived from the Bird base class) to a pointer
to the <b>Bird </b>base class:</p>

<p><b>Bird *pBird = new Pigeon;</b></p>

<p>Almost magically, this pointer can be used to access regular methods of the
Bird base class and overriding methods of the derived Pigeon class.</p>

<p>The example listed demonstrates this technique in action. Two methods named
<b>Walk </b>and <b>Talk</b> are declared in the base class - but only <b>Talk
</b>is a virtual method. When the Talk method is called it executes the
overriding method in the derived class, rather than the default statement in
the base class, unless the base method is called explicitly.</p>

Z 6af9b177f5f80cb705a9703aac0a6fb1