CSE2305 - Object-Oriented Software Engineering
Week 5

Topic 10: C++ Polymorphism


Synopsis


Pointers, references¤ and inheritance



Polymorphism¤ in C++



Virtual functions¤



An example

class Vehicle
{
public:
	Vehicle(char* regnum)
        : myRegNum(strdup(regnum))
        {}

	~Vehicle(void)
        { delete[] myRegNum; }

	virtual void Describe(void)
        {
                cout << "Unknown vehicle, registration "
                     << myRegNum << endl;
        }

protected:
	char* myRegNum;
};

class Car : public Vehicle
{
public:
	Car(char* make, char* regnum)
        : Vehicle(regnum), myMake( strdup(make) )
        {}

	~Car(void)
        { delete[] myMake; }

	virtual void Describe(void)
        {
                cout << "Car (" << myMake
		     << "), registration "
		     << myRegNum << endl;
        }

protected:
	char* myMake;
};

Vehicle* vp1 = new Car ("Jaguar","XJS 012");
Vehicle* vp2 = new Vehicle ("SGI 987");
Vehicle* vp3 = new Vehicle ("ABC 123");

vp1->Describe();		// PRINTS "Car (Jaguar)....."
vp2->Describe();		// PRINTS "Unknown vehicle....."
vp3->Describe();		// PRINTS "Unknown vehicle....."

How virtual functions¤ work


        [Diagram showing the pointers vp1, vp2, and vp3, all pointing to objects
         containing vtable pointers.  These pointers point at separate
         class-specific vtables (one for Vehicle, one for Car).  The first
         element of each vtable points at the corresponding Describe() member
         function.]


Virtual destructors¤¤



Reading


This material is part of the CSE2305 - Object-Oriented Software Engineering course.
Copyright © Jon McCormack & Damian Conway, 1998–2005. All rights reserved.