Inheritance - Kamills-12/2143-OOP GitHub Wiki
Inheritance is just reusing code from another class. That’s it.
One class (child) borrows everything from another class (parent). You don’t start from scratch, you pick up from what’s already there.
Think: You’re not writing a whole new car class for “ElectricCar.” Just take “Car” and add a battery.
- You want to reuse code and not repeat yourself.
- You want different types of things to share the same behavior.
- You want to build off something without wrecking the original.
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Woof!" << endl;
}
};
int main() {
Dog myDog;
myDog.eat(); // inherited from Animal
myDog.bark(); // dog's own thing
return 0;
}