Create an abstract class Employee with a pure virtual function calculateSalary(). Derive two classes FullTime and PartTime from it. Implement salary calculation logic differently in each class and display the salary using base class pointer.

SOLUTION....


#include <iostream>
using namespace std;

// Abstract base class
class Employee {
protected:
    string name;
    int id;
public:
    Employee(string n, int i) : name(n), id(i) {}
    virtual void calculateSalary() = 0;  // Pure virtual function
    virtual void display() {
        cout << "Employee ID: " << id << endl;
        cout << "Name: " << name << endl;
    }
};

// Derived class: FullTime
class FullTime : public Employee {
private:
    float basic, allowance;
public:
    FullTime(string n, int i, float b, float a)
        : Employee(n, i), basic(b), allowance(a) {}

    void calculateSalary() override {
        float salary = basic + allowance;
        display();
        cout << "Type: Full-Time" << endl;
        cout << "Salary = " << salary << endl;
        cout << "----------------------" << endl;
    }
};

// Derived class: PartTime
class PartTime : public Employee {
private:
    int hours;
    float payPerHour;
public:
    PartTime(string n, int i, int h, float p)
        : Employee(n, i), hours(h), payPerHour(p) {}

    void calculateSalary() override {
        float salary = hours * payPerHour;
        display();
        cout << "Type: Part-Time" << endl;
        cout << "Salary = " << salary << endl;
        cout << "----------------------" << endl;
    }
};

// Main function
int main() {
    Employee* emp;  // Base class pointer

    FullTime f1("Hardik", 101, 30000, 5000);
    PartTime p1("Raj", 102, 40, 200);

    emp = &f1;
    emp->calculateSalary();  // Calls FullTime version

    emp = &p1;
    emp->calculateSalary();  // Calls PartTime version

    return 0;
}

OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.