C++ Inheritance
What is Inheritance?
Inheritance allows a derived class (child) to acquire the properties and methods of a base class (parent). It promotes code reuse and establishes an "is-a" relationship.
Syntax: class Derived : accessSpecifier Base { ... };
| Inheritance Type | public members become | protected members become |
|---|---|---|
public | public in derived | protected in derived |
protected | protected in derived | protected in derived |
private | private in derived | private in derived |
#include <iostream>
#include <string>
using namespace std;
// Base class
class Animal {
protected:
string name;
int age;
public:
Animal(string name, int age) : name(name), age(age) {}
void eat() { cout << name << " is eating" << endl; }
void sleep() { cout << name << " is sleeping" << endl; }
void info() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
// Derived class — inherits from Animal
class Dog : public Animal {
private:
string breed;
public:
// Call base constructor via initializer list
Dog(string name, int age, string breed)
: Animal(name, age), breed(breed) {}
void bark() { cout << name << " says: Woof!" << endl; }
void info() { // override base info()
Animal::info(); // call base version
cout << "Breed: " << breed << endl;
}
};
int main() {
Dog d("Rex", 3, "German Shepherd");
d.eat(); // inherited from Animal
d.sleep(); // inherited from Animal
d.bark(); // Dog's own method
d.info(); // Dog's overridden info()
return 0;
}
Multilevel and Multiple Inheritance
#include <iostream>
using namespace std;
class Vehicle {
public:
void start() { cout << "Vehicle started" << endl; }
};
class Car : public Vehicle {
public:
void drive() { cout << "Car driving" << endl; }
};
// Multilevel: ElectricCar → Car → Vehicle
class ElectricCar : public Car {
public:
void charge() { cout << "Charging battery" << endl; }
};
int main() {
ElectricCar ec;
ec.start(); // from Vehicle
ec.drive(); // from Car
ec.charge(); // own method
return 0;
}
#include <iostream>
using namespace std;
class Flyable {
public:
void fly() { cout << "Flying" << endl; }
};
class Swimmable {
public:
void swim() { cout << "Swimming" << endl; }
};
// Multiple inheritance: Duck inherits from both
class Duck : public Flyable, public Swimmable {
public:
void quack() { cout << "Quack!" << endl; }
};
int main() {
Duck d;
d.fly(); // from Flyable
d.swim(); // from Swimmable
d.quack(); // own method
return 0;
}