You are on page 1of 5

Object Oriented Programming

Lab Manual (Lab 10)

Topic: Polymorphism & Abstract Classes

Lab Instructor:Ahmad Abduhu

Session: Spring 2020

School of Systems and Technology


UMT Lahore Pakistan

1
Objectives

The objective of this lab is to get familiar you with the pure virtual functions, abstract class, pure
abstract base class and polymorphism and their implementation in C++.

Sample Code 1 :

// Demonstrate why we need a virtual function and pure virtual functions.

#include <iostream>
using namespace std;

class Shape {
protected:
int width, height;

public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};

class Triangle: public Shape {


public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};

// Main function for the program


int main() {
2
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);

// store the address of Rectangle


shape = &rec;

// call rectangle area.


shape->area();

// store the address of Triangle


shape = &tri;

// call triangle area.


shape->area();

return 0;
}

Sample Code 2 :

// Demonstrate the abstract classes

#include <iostream>
using namespace std;
class Base
{
public:
virtual void print() const = 0;
};
class DerivedOne : virtual public Base
{
public:
void print() const
{
cout<< "DerivedOne\n";
}
};
class DerivedTwo : virtual public Base
{
public:
void print() const
{
cout<< "DerivedTwo\n";
}
};
3
class Multiple : public DerivedOne, DerivedTwo
{
public:
void print() const
{
DerivedTwo::print();
}
};
int main()
{
Multiple both;
DerivedOne one;
DerivedTwo two;
Base *array[ 3 ];
array[ 0 ] = &both;
array[ 1 ] = &one;
array[ 2 ] = &two;

for ( int i = 0; i< 3; i++ )


array[ i ] -> print();
return 0;

4
Lab Tasks
Task 1:

Create parent class Polygon with protected parameters width and height and function
printarea() and a virtual function area(). Create three sub classes Rectangle , Square and
Triangle.
In main() create 3 pointers of Polygon and assign Rectangle , Square and Triangle to it. Call
printarea function with the pointers

Task 2:

(Simple Payroll Application) Develop a simple payroll application. There are three kinds of
employees in the system: salaried employee, hourly employee, and commissioned
employee. The system takes input as an array containing employee objects, calculates
salary polymorphically, and generates report.

You might also like