Skip to content

Instantly share code, notes, and snippets.

@suragch
Created May 6, 2022 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suragch/3d5687efa35bf7316cf529a73ae1c9d5 to your computer and use it in GitHub Desktop.
Save suragch/3d5687efa35bf7316cf529a73ae1c9d5 to your computer and use it in GitHub Desktop.
Polymorphism
#include <iostream>
#include <regex>
using namespace std;
class AbstractEmployee
{
// Returns true if got promotion
virtual bool RequestPromotion() = 0;
virtual void Work() = 0;
};
class Employee : AbstractEmployee
{
private:
string Company;
int Age;
protected:
string Name;
public:
// constructor
Employee(string name, string company, int age)
{
Name = name;
Company = company;
Age = age;
}
// Setters and getters
void setName(string value)
{
if (value.length() > 50)
{
return;
}
auto nameMatch = regex("^[a-zA-Z]+$");
if (!regex_match(value, nameMatch))
{
return;
}
Name = value;
}
string getName()
{
return Name;
}
void setCompany(string company)
{
Company = company;
}
string getCompany()
{
return Company;
}
void setAge(int value)
{
if (value < 0)
{
return;
}
Age = value;
}
int getAge()
{
return Age;
}
void Introduce()
{
cout << Name << ", age " << Age << ", works at " << Company << ".\n";
}
bool RequestPromotion()
{
if (Age < 30)
{
cout << Name << " did not get promoted.\n";
return false;
}
else
{
cout << Name << " got promoted.\n";
return true;
}
}
void Work() {
cout << Name << " is working.\n";
}
};
// Developer = child class, subclass
// Employee = parent class, super class
class Developer : public Employee
{
string FavoriteLanguage;
public:
Developer(string name, string company, int age, string favoriteLanguage)
: Employee(name, company, age)
{
FavoriteLanguage = favoriteLanguage;
}
string getFavoriteLanguage()
{
return FavoriteLanguage;
}
void fixBug()
{
// Jonathan fixed a bug using Dart.
cout << Name << " fixed a bug using " << FavoriteLanguage << ".\n";
}
void Introduce()
{
cout << Name << "'s favorite language is " << FavoriteLanguage << ".\n";
}
void Work() {
fixBug();
}
};
// Teacher
class Teacher : public Employee {
string Subject;
public:
Teacher(string name, string company, int age, string subject)
: Employee(name, company, age)
{
Subject = subject;
}
void prepareLesson() {
cout << Name << " is preparing a " << Subject << " lesson.\n";
}
void Work() {
prepareLesson();
}
};
int main()
{
Employee bob = Employee("Bob", "Starbucks", 18);
Employee mary = Employee("Mary", "Facebook", 30);
Employee me = Developer("Jonathan", "SEU", 44, "Dart");
Employee susan = Teacher("Susan", "Super High School", 51, "math");
bob.Work();
mary.Work();
me.Work();
susan.Work();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment