Lab 9
Polymorphism
Objectives
Following programming skills will be acquired in this lab:
To understand the use of pointer to a base class.
To practice the syntax of defining a virtual function.
To understand use of abstract classes.
To understand the use of pure virtual functions.
Pointers to Base Class
One of the key features of derived classes is that a pointer to a derived class is type-compatible with a
pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and
versatile feature, that brings Object Oriented Methodologies to its full potential.
Example 9.1: Pointers to Base Class
#include <iostream> Output:
using namespace std;
20
class CPolygon { 10
protected:
int width, height;
public:
void setValues (int a, int b)
{ width=a; height=b; }
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
ppoly1->setValues (4,5);
ppoly2->setValues (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
Virtual Members
A member of a class that can be redefined in its derived classes is known as a virtual member. In order
to declare a member of a class as virtual, we must precede its declaration with the keyword virtual. A
class that declares or inherits a virtual function is called a polymorphic class.Note that despite of its
virtuality, we have also been able to declare an object of type CPolygon and to call its own area() function,
which always returns 0.
Example 9.2
#include <iostream>
using namespace std; ppoly1->setValues (4,5);
ppoly2->setValues (4,5);
class CPolygon { ppoly3->setValues (4,5);
protected:
int width, height; cout << ppoly1->area() << endl;
public: cout << ppoly2->area() << endl;
void setValues (int a, int b) cout << ppoly3->area() << endl;
{ width=a; height=b; } return 0;
}
virtual int area ()
{ return (0); }
}; Output:
class CRectangle: public CPolygon { 20
public: 10
int area () 0
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};
int main ()
{
CRectangle rect;
CTriangle trgl;
CPolygon poly;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
CPolygon * ppoly3 = &poly;
Example 9.3 Virtual Functions Assessed with Pointers
Pure Virtual Function
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have
implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration.
Abstract Base Classes
An abstract class is a class that is designed to be specifically used as a base class. An abstract class
contains at least one pure virtual function. We cannot creat objects of an abstract class.
Virtual members and abstract classes grant C++ the polymorphic characteristics that make object-oriented
programming such a useful instrument in big projects.
Example 9.4
#include <iostream> Output:
using namespace std;
20
class CPolygon 10
{
protected:
int width, height;
public:
void setValues (int a, int b)
{ width=a; height=b; }
virtual int area (void) = 0;
void printarea (void) { cout << this->area() << endl; }
};
class CRectangle: public CPolygon {
public:
int area (void) { return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area (void) { return (width * height / 2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
ppoly1->setValues (4,5);
ppoly2->setValues (4,5);
ppoly1->printarea();
ppoly2->printarea();
return 0;
}
Example 9.5 Using Abstract Base Class
#include <iostream> bool isOutstanding()
using namespace std; { return (numPubs > 100) ? true : false; }
class person //person class int main()
{ {
protected: person* persPtr[10];
char name[40]; int n = 0;
public: char choice;
void getName() do
{ cout << "Enter name: "; cin >> name; } {
void putName() cout << "Enter student or professor (s/p):
{ ";
cout << "Name is: " << name << endl; } cin >> choice;
virtual void getData() = 0; //pure virtual if(choice=='s')
virtual bool isOutstanding() = 0; //pure persPtr[n] = new student;
}; else
persPtr[n] = new professor;
class student : public person persPtr[n++]->getData();
{ cout << "Enter another (y/n)? ";
private: cin >> choice;
float gpa; }
public:
void getData() while( choice=='y' );
{ for(int j=0; j<n; j++)
person::getName(); {
cout << "Enter student’s GPA: "; cin >> persPtr[j]->putName();
gpa; if( persPtr[j]->isOutstanding() )
}
bool isOutstanding() cout << "This person is outstanding\n";
{ return (gpa > 3.5) ? true : false; } }
};
return 0;
class professor : public person }
{
private:
int numPubs;
public:
void getData()
{
person::getName();
cout << "Enter number of professor's
publications: ";
cin >> numPubs;
}
};
Example 9.6
#include <iostream>
using namespace std;
class vehicle
{ int wheels;
float weight;
public:
virtual void message(void)
{cout<<"Vehicle message, from vehicle, the base class\n";}
};
class car :public vehicle
{ int passengerLoad;
public:
void message(void) // second message()
{cout<<"Car message, from car, the vehicle derived class\n";}
};
class truck : public vehicle
{ int passengerLoad;
floatpayload;
public:
int passengers(void) {return passengerLoad;}
};
class boat : public vehicle
{ int passengerLoad;
public:
int passengers(void) {return passengerLoad;}
void message(void) // third message()
{cout<<"Boat message, from boat, the vehicle derived class\n";}
};
int main()
{ vehicle unicycle;
car sedanCar;
truck trailer;
boat sailboat;
cout<<"Adding virtual keyword at the base class method\n";
cout<<" \n";
unicycle.message();
sedanCar.message();
trailer.message();
sailboat.message();
system("pause");
return 0;
}
Exercises
Exercise 9.1
Create an abstract class Faculty with the fields name and ID. Provide a pure virtual function salary (). Derive
a class Permanent Faculty from Faculty. The class has additional attributes years of service and basic pay.
The salary of permanent faculty is computed as the sum of basic pay, medical allowance and house rent.
Medical allowance is 10% of basic pay and house rent is 25% of the basic pay.
Derive another class visiting faculty from Faculty. The class has attributes per hour rate and number of
hours taught. The salary of visiting faculty is computed by multiplying the per hour rate with the number
of hours taught.
Write a program to declare two pointers of class Faculty. Create an object each of visiting and permanent
faculty, as sign their addresses to pointers of base class, set the value of data members and call the salary
function for each.
Exercise 9.2
Modify the above program to declare an array of pointers to Faculty. Using dynamic memory allocation,
create an object of permanent or visiting faculty as indicated by the user (get user choice).Once the user has
entered data for faculty, call the salary method for each object and display the salary.