C++ Inheritance — Complete Beginner Guide
Learning Objectives
- Build a derived class from a base class
- Distinguish single and multilevel inheritance
- Apply public, protected, and private access
- Call base constructors from a derived class
Why Inheritance Exists
Inheritance lets one class reuse and extend another. Shared behavior lives in a base class, also called a parent. A derived class, also called a child, adds or refines features. You model an is a relationship, such as a dog being an animal.
Single Inheritance
Single inheritance means one parent and one child.
#include <iostream>
#include <string>
class Animal {
public:
std::string name;
void eat() {
std::cout << name << " eats." << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << name << " says woof." << std::endl;
}
};
int main() {
Dog d;
d.name = "Rex";
d.eat();
d.bark();
return 0;
}
The colon introduces the base class. With public inheritance, public members of Animal stay public in Dog.
Multilevel Inheritance
A chain of parents creates a multilevel hierarchy. Members flow down each link.
class LivingThing {
public:
void live() { /* shared behavior */ }
};
class Animal : public LivingThing {
public:
void move() { /* animal behavior */ }
};
class Bird : public Animal {
public:
void fly() { /* bird behavior */ }
};
Bird gains access to move and live through its ancestry. Keep hierarchies shallow when you can, because deep chains grow hard to trace.
Access Specifiers
Access controls who may touch a member.
| Specifier | Same Class | Derived Class | Outside World |
|---|---|---|---|
| public | Yes | Yes | Yes |
| protected | Yes | Yes | No |
| private | Yes | No | No |
With public inheritance, base public members remain public and base protected members remain protected in the child. Private base members stay private to the base and are not directly usable by the child body.
Calling Base Constructors
Derived objects create the base part first. You pass base arguments through the initialization list.
class Vehicle {
public:
int wheels;
Vehicle(int w) : wheels(w) {}
};
class Car : public Vehicle {
public:
std::string brand;
Car(std::string b) : Vehicle(4), brand(b) {}
};
If a base has no default constructor, the derived constructor must supply arguments explicitly. Forgetting this is a frequent compile error.
Using the Base Part Explicitly
Inside a derived method, the base implementation can be reached with a qualified name.
class Bird : public Animal {
public:
void describe() {
eat(); // inherited
std::cout << "and flies" << std::endl;
}
};
When a derived function replaces a base function of the same name, the derived version wins for calls through the derived type. Virtual functions in the next lessons extend that behavior to base type pointers and references.
Protected Members
Protected members exist for collaboration between related classes without exposing the world.
class Shape {
protected:
double areaValue = 0.0;
public:
double getArea() const { return areaValue; }
};
class Square : public Shape {
public:
void compute(double side) {
areaValue = side * side;
}
};
Outside code still cannot write areaValue directly, but Square can maintain it.
Is a Versus Has a
| Relationship | Tool | Example |
|---|---|---|
| is a | Inheritance | Car is a Vehicle |
| has a | Composition | Car has an Engine |
Prefer composition when the child is only using another object rather than being a specialized version of it. Overusing inheritance creates fragile designs.
Multiple Inheritance Note
C plus plus allows a class to list more than one base. That can create ambiguity when two parents share a member. Most beginner projects should stick to a single base to avoid diamond complications until interfaces and virtual bases are clear.
Common Mistakes
| Mistake | Result |
|---|---|
| Forgetting colon syntax | Parse error |
| Wrong access override | Members become less visible than intended |
| Missing base constructor args | Compile error |
| Deep unnecessary hierarchy | Confusing design |
| Public everything | Broken encapsulation |
A Worked Example
#include <iostream>
#include <string>
class Account {
public:
std::string owner;
double balance;
Account(std::string o, double b) : owner(o), balance(b) {}
void deposit(double amount) {
if (amount > 0) balance += amount;
}
};
class SavingsAccount : public Account {
public:
double rate;
SavingsAccount(std::string o, double b, double r)
: Account(o, b), rate(r) {}
};
int main() {
SavingsAccount s("Mia", 100.0, 0.03);
s.deposit(50.0);
std::cout << s.owner << " has " << s.balance << std::endl;
return 0;
}
The child focuses on savings specific fields while reusing deposit and shared state.
Key Takeaways
💡
- Inheritance models an is a relationship and reuses shared design
- public, protected, and private control visibility across layers
- Derived constructors must initialize base parts correctly
- Prefer shallow hierarchies and composition over deep inheritance
- Match access specifiers to intent instead of defaulting blindly
Practice Questions
- Create a base class Employee and a derived class Manager with an extra field.
- What is the difference between public and protected members for outside code?
- When is composition a better choice than inheritance?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions