Object Oriented Programming Lab-10 (Polymorphism and Abstract Classes)
Object Oriented Programming Lab-10 (Polymorphism and Abstract Classes)
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 :
#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);
}
};
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
return 0;
}
Sample Code 2 :
#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;
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.