fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. // Base class
  6. class Employee {
  7. protected:
  8. string name;
  9. int id;
  10.  
  11. public:
  12. Employee(string n, int i) {
  13. name = n;
  14. id = i;
  15. }
  16.  
  17. virtual void calculateSalary() = 0; // Pure virtual function
  18.  
  19. void displayInfo() {
  20. cout << "Name: " << name << ", ID: " << id << endl;
  21. }
  22. };
  23.  
  24. // Derived class for Faculty
  25. class Faculty : public Employee {
  26. private:
  27. int coursesTaught;
  28. double salaryPerCourse;
  29.  
  30. public:
  31. Faculty(string n, int i, int courses, double perCourse)
  32. : Employee(n, i), coursesTaught(courses), salaryPerCourse(perCourse) {}
  33.  
  34. void calculateSalary() {
  35. double salary = coursesTaught * salaryPerCourse;
  36. cout << "Faculty Salary: $" << salary << endl;
  37. }
  38. };
  39.  
  40. // Derived class for Staff
  41. class Staff : public Employee {
  42. private:
  43. double hourlyWage;
  44. int hoursWorked;
  45.  
  46. public:
  47. Staff(string n, int i, double wage, int hours)
  48. : Employee(n, i), hourlyWage(wage), hoursWorked(hours) {}
  49.  
  50. void calculateSalary() {
  51. double salary = hourlyWage * hoursWorked;
  52. cout << "Staff Salary: $" << salary << endl;
  53. }
  54. };
  55.  
  56. // Main function to demonstrate the hierarchy
  57. int main() {
  58. // Creating Faculty object
  59. Faculty faculty("Dr. Smith", 101, 3, 2000.0);
  60. faculty.displayInfo();
  61. faculty.calculateSalary();
  62.  
  63. // Creating Staff object
  64. Staff staff("John Doe", 201, 15.0, 160);
  65. staff.displayInfo();
  66. staff.calculateSalary();
  67.  
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0.01s 5268KB
stdin
Standard input is empty
stdout
Name: Dr. Smith, ID: 101
Faculty Salary: $6000
Name: John Doe, ID: 201
Staff Salary: $2400