2080 2

BIT153 ยท 2080 ยท 10 marks

What is Polymorphism in Object Oriented Programming? Implement a class Employee with a virtual function CalculateSalary() that returns the salary of the employee. Create two derived classes HourlyEmployee and SalariedEmployee. Override the CalculateSalary() function in both derived classes to calcul

What is Polymorphism in Object Oriented Programming? Implement a class Employee with a virtual function CalculateSalary() that returns the salary of the employee. Create two derived classes HourlyEmployee and SalariedEmployee. Override the CalculateSalary() function in both derived classes to calculate the salary of an hourly employee and a salaried employee respectively. Write a program that creates objects of both derived classes and calls the CalculateSalary() function for each.[10]

Object Oriented ProgrammingChapter 8: Static and Dynamic PolymorphismVirtual functions

Quick answer

Polymorphism is one of the four fundamental pillars of Object Oriented Programming (along with Encapsulation, Inheritance, and Abstraction). The word polymorphism comes from Greek meaning "many forms".

Polymorphism in OOP and Virtual Function Implementation

What is Polymorphism?

In OOP, polymorphism means the ability of a single interface (function name or operator) to behave differently depending on the object that invokes it.

Types of Polymorphism

TypeAlso Known AsResolved At
Compile-time PolymorphismStatic / Early BindingCompile time
Run-time PolymorphismDynamic / Late BindingRun time
  • Compile-time polymorphism is achieved through function overloading and operator overloading.
  • Run-time polymorphism is achieved through virtual functions and function overriding (inheritance).

Key Concepts for Run-time Polymorphism

  • Virtual Function: A function declared with the keyword virtual in the base class. It tells the compiler to resolve the function call at run time based on the actual object type, not the pointer/reference type.
  • Override: Redefining a virtual function in a derived class with the same signature.
  • Base class pointer can point to derived class objects, and the correct overridden function is called automatically (dynamic dispatch).

C++ Program Implementation

#include <iostream>
using namespace std;

// -----------------------------------------------
// Base Class: Employee
// -----------------------------------------------
class Employee {
protected:
    string name;

public:
    // Constructor
    Employee(string empName) {
        name = empName;
    }

    // Virtual function to be overridden in derived classes
    virtual double CalculateSalary() {
        return 0.0;
    }

    // Virtual display function
    virtual void display() {
        cout << "Employee Name : " << name << endl;
        cout << "Salary        : Rs. " << CalculateSalary() << endl;
    }

    // Virtual destructor (good practice with virtual functions)
    virtual ~Employee() {}
};

// -----------------------------------------------
// Derived Class 1: HourlyEmployee
// Salary = hoursWorked * hourlyRate
// -----------------------------------------------
class HourlyEmployee : public Employee {
private:
    double hoursWorked;
    double hourlyRate;

public:
    // Constructor
    HourlyEmployee(string empName, double hours, double rate)
        : Employee(empName) {
        hoursWorked = hours;
        hourlyRate  = rate;
    }

    // Override CalculateSalary()
    double CalculateSalary() override {
        return hoursWorked * hourlyRate;
    }

    void display() override {
        cout << "----- Hourly Employee -----" << endl;
        cout << "Employee Name : " << name        << endl;
        cout << "Hours Worked  : " << hoursWorked << endl;
        cout << "Hourly Rate   : Rs. " << hourlyRate << endl;
        cout << "Total Salary  : Rs. " << CalculateSalary() << endl;
    }
};

// -----------------------------------------------
// Derived Class 2: SalariedEmployee
// Salary = fixedMonthlySalary (fixed, no calculation needed)
// -----------------------------------------------
class SalariedEmployee : public Employee {
private:
    double monthlySalary;

public:
    // Constructor
    SalariedEmployee(string empName, double salary)
        : Employee(empName) {
        monthlySalary = salary;
    }

    // Override CalculateSalary()
    double CalculateSalary() override {
        return monthlySalary;
    }

    void display() override {
        cout << "----- Salaried Employee -----" << endl;
        cout << "Employee Name   : " << name          << endl;
        cout << "Monthly Salary  : Rs. " << CalculateSalary() << endl;
    }
};

// -----------------------------------------------
// Main Function
// -----------------------------------------------
int main() {

    // Create objects of derived classes
    HourlyEmployee  emp1("Ram Sharma",   160, 150.0);  // 160 hrs, Rs.150/hr
    SalariedEmployee emp2("Sita Thapa",  55000.0);     // Fixed Rs.55000/month

    // Call display (which internally calls CalculateSalary)
    emp1.display();
    cout << endl;
    emp2.display();
    cout << endl;

    // Demonstrating Run-time Polymorphism using Base class pointer
    cout << "=== Run-time Polymorphism Demo ===" << endl;

    Employee* empPtr;   // Base class pointer

    empPtr = &emp1;     // Points to HourlyEmployee object
    cout << "Salary (via base pointer): Rs. " << empPtr->CalculateSalary() << endl;

    empPtr = &emp2;     // Points to SalariedEmployee object
    cout << "Salary (via base pointer): Rs. " << empPtr->CalculateSalary() << endl;

    return 0;
}

Expected Output

----- Hourly Employee -----
Employee Name : Ram Sharma
Hours Worked  : 160
Hourly Rate   : Rs. 150
Total Salary  : Rs. 24000

----- Salaried Employee -----
Employee Name   : Sita Thapa
Monthly Salary  : Rs. 55000

=== Run-time Polymorphism Demo ===
Salary (via base pointer): Rs. 24000
Salary (via base pointer): Rs. 55000

Explanation of Key Points

ConceptWhere Used
virtual keywordDeclared in Employee::CalculateSalary()
override keywordUsed in both derived classes (C++11)
Dynamic DispatchBase class pointer empPtr calls correct version at run time

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.