Abstract Classes - Kamills-12/2143-OOP GitHub Wiki
An abstract class is a base class that’s never meant to be used directly. It’s more like a template for other classes to build from.
What makes a class “abstract”?
It has at least one pure virtual function, which means any class that inherits from it has to implement that function.
- You want to set rules for your subclasses.
- You want to share code.
- It helps with abstraction by hiding details and only exposing what the child classes need.
#include <iostream>
using namespace std;
// Abstract class
class Weapon {
public:
virtual void attack() = 0; // pure virtual function
void reload() {
cout << "Reloading..." << endl;
}
virtual ~Weapon() = default;
};
// Concrete class
class Sword : public Weapon {
public:
void attack() override {
cout << "Swinging sword!" << endl;
}
};
class Bow : public Weapon {
public:
void attack() override {
cout << "Firing arrow!" << endl;
}
};
int main() {
Weapon* w1 = new Sword();
Weapon* w2 = new Bow();
w1->attack(); // Swinging sword!
w2->attack(); // Firing arrow!
w1->reload(); // Inherited method
delete w1;
delete w2;
return 0;
}