⚡C++IntermediateLesson 27 of 50CamboFreelanceJune 19, 2026
C++ Inheritance
Learn C++ inheritance: derive classes from a base class, reuse code, call base constructors, and build class hierarchies.
Intermediate9 min readLesson 27 of 50
What is Inheritance?
Inheritance lets a class (child/derived) acquire attributes and methods of another class (parent/base), promoting code reuse.
class DerivedClass : accessSpecifier BaseClass { };
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
string name;
void eat() { cout << name << " is eating." << endl; }
void sleep() { cout << name << " is sleeping." << endl; }
};
// Derived class
class Dog : public Animal {
public:
void bark() { cout << name << " says: Woof!" << endl; }
};
class Cat : public Animal {
public:
void meow() { cout << name << " says: Meow!" << endl; }
};
int main() {
Dog d; d.name = "Rex";
d.eat(); // inherited from Animal
d.bark(); // Dog's own method
Cat c; c.name = "Whiskers";
c.sleep(); // inherited
c.meow();
return 0;
}
Output:
Rex is eating.
Rex says: Woof!
Whiskers is sleeping.
Whiskers says: Meow!
Constructor Inheritance
The derived constructor calls the base constructor using the initializer list:
class Vehicle {
public:
string brand;
Vehicle(string b) : brand(b) { }
};
class ElectricCar : public Vehicle {
public:
int range;
ElectricCar(string b, int r) : Vehicle(b), range(r) { }
void info() {
cout << brand << " — Range: " << range << "km" << endl;
}
};
ElectricCar tesla("Tesla", 600);
tesla.info(); // Tesla — Range: 600km
Exercise
Create a base class Shape with a color attribute and a describe() method. Derive Circle (with radius) and Square (with side), each with an area() method.
Show Solution
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
string color;
Shape(string c) : color(c) { }
void describe() { cout << "Color: " << color << endl; }
};
class Circle : public Shape {
public:
double radius;
Circle(string c, double r) : Shape(c), radius(r) { }
double area() { return 3.14159 * radius * radius; }
};
class Square : public Shape {
public:
double side;
Square(string c, double s) : Shape(c), side(s) { }
double area() { return side * side; }
};
int main() {
Circle ci("Red", 5);
ci.describe();
cout << "Circle area: " << ci.area() << endl;
Square sq("Blue", 4);
sq.describe();
cout << "Square area: " << sq.area() << endl;
return 0;
}
Quiz
Which keyword is used to inherit from a base class?
A) extends
B) inherits
C) : (colon)
D) <<
Answer
C) Colon — e.g., class Dog : public Animal.
Summary
Inheritance enables a derived class to reuse base class members.
Use class Child : public Parent syntax.
Derived constructors call base constructors via initializer lists.