Inheritance and virtual functions
Reuse code, and let each class supply its own behaviour.
C++
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Staff {
public:
virtual ~Staff() = default;
virtual int pay() const = 0;
};
class Developer : public Staff {
public:
int pay() const override { return 30000; }
};
class Intern : public Staff {
public:
int pay() const override { return 5000; }
};
int main() {
vector<unique_ptr<Staff>> team;
team.push_back(make_unique<Developer>());
team.push_back(make_unique<Intern>());
for (const auto &s : team) {
cout << s->pay() << "\n";
}
return 0;
}Output
30000 5000
virtual picks the right version at run time, and = 0 makes the class abstract. A base class needs a virtual destructor. unique_ptr frees the object automatically, so you do not need new and delete.