CS 202 Fall 2013 > Notes for Tuesday, October 15, 2013 |
CS 202 Fall 2013
Notes for Tuesday, October 15, 2013
Object-Oriented Programming: Virtual Functions & Polymorphism [15.6]
Polymorphism
We want to be able to deal with an object without knowing what its type is, and have the object behave accordingly (i.e., using the member functions of its own type). This is called polymorphism.
In C++ polymorphism is enabled through two mechanisms: inheritance and virtual functions.
We have already seen (public) inheritance We make a derived class out of a base class. All members of the base class become members of the derived class, with the public members still public in the derived class.
Virtual Functions
A virtual function allows for a derived-class member function to be called when an object is referenced through a base-class pointer or reference.
We make a member function virtual by
placing the keyword virtual
before its declaration inside (but not outside!) a class
definition.
[C++]
class Writer { public: ... // Parts left out? void misquote() const // Not virtual { cout << "Weigh it again, Sam." << endl; } virtual void identify() const; // Virtual }; // This is a virtual function, but we do not say "virtual" here void Writer::identify() const { cout << "<generic writing thing>" << endl; }
Now if we use Writer
as a base class,
we can call a derived-class version of function identify
using a base-class pointer or reference.
First, we need a derived class.
[C++]
class Pen : public Writer { public: ... void misquote() const { cout << "Use the horse, Duke!" << endl; } virtual void identify() const { cout << "This here's a pen." << endl; } };
We can use both classes in the ordinary way.
The magic happens if we use a
pointer or reference to Writer
to refer to an object of type Pen
[C++]
void doMisquote(const Writer & w) { w.misquote(); } void doIdentify(const Writer & w) { w.identify(); } int main() { Writer w; Pen p; doMisquote(w); // Prints "Weight it again, Sam" doMisquote(p); // Prints "Weight it again, Sam" // Remember: misquote is not a virtual function doIdentify(w); // Prints "<generic writing thing>" doIdentify(p); // Prints "This here's a pen." }
Virtual Destructor
When a class is to be used in an inheritance hierarchy, it should always be given a virtual destructor, so that derived-class objects can be cleaned up properly (if necessary). Usually, we do not write a destructor at all, since there i usually nothing for it to do. In such cases, simply write a virtual destructor with an empty function body.
[C++]
class Writer { public: virtual ~Writer() {} ... }; class Pen { public: virtual ~Pen() {} ... };
Note: constructors cannot be virtual; when we construct an object, we always specify its type. But this is not true of the destructor.
For today’s lab work, see the 10/15 Challenge.