Why inheritance is used in C++ - Performance Analysis
We want to understand how using inheritance affects the time it takes for a program to run.
Specifically, how does calling functions through inheritance change the work done as the program grows?
Analyze the time complexity of this simple inheritance example.
class Animal {
public:
virtual void speak() { }
};
class Dog : public Animal {
public:
void speak() override { /* bark */ }
};
void makeSpeak(Animal* animals[], int n) {
for (int i = 0; i < n; ++i) {
animals[i]->speak();
}
}
This code calls the speak function on an array of Animal pointers, which may point to different derived types.
Look for repeated actions that take time.
- Primary operation: Loop through the array and call speak() on each object.
- How many times: Exactly once per element, so n times.
As the number of animals grows, the number of speak calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 speak calls |
| 100 | 100 speak calls |
| 1000 | 1000 speak calls |
Pattern observation: The work grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of objects increases.
[X] Wrong: "Inheritance makes the program slower in a way that grows faster than the number of objects."
[OK] Correct: Each call through inheritance still happens once per object, so the total work grows linearly, not faster.
Understanding how inheritance affects time helps you explain your design choices clearly and confidently.
"What if the speak function called another function inside a loop? How would that change the time complexity?"
Practice
Solution
Step 1: Understand inheritance purpose
Inheritance allows a new class to use code from an existing class, avoiding repetition.Step 2: Analyze options
Only To reuse code from an existing class correctly states code reuse. Others are unrelated or incorrect.Final Answer:
To reuse code from an existing class -> Option BQuick Check:
Inheritance = Code reuse [OK]
- Thinking inheritance speeds up program execution
- Confusing inheritance with unrelated class creation
- Believing inheritance removes need for functions
Car that inherits from class Vehicle in C++?Solution
Step 1: Recall C++ inheritance syntax
In C++, inheritance is declared using a colon and access specifier likepublic.Step 2: Check each option
class Car : public Vehicle {};uses correct syntax.inheritsandextendsuse keywords from other languages.class Car Vehicle {};is invalid.Final Answer:
class Car : public Vehicle {}; -> Option DQuick Check:
C++ inheritance syntax = colon + access specifier [OK]
- Using 'inherits' or 'extends' keywords (not C++ syntax)
- Omitting colon before base class name
- Forgetting access specifier like public
class Animal {
public:
void sound() { std::cout << "Animal sound"; }
};
class Dog : public Animal {
public:
void sound() { std::cout << "Bark"; }
};
int main() {
Dog d;
d.sound();
return 0;
}What is the output when this program runs?
Solution
Step 1: Understand method overriding in inheritance
TheDogclass defines its ownsound()method, which overridesAnimal's method.Step 2: Check which method is called
Callingd.sound()usesDog's version, printing "Bark".Final Answer:
Bark -> Option AQuick Check:
Overridden method runs = Bark [OK]
- Assuming parent method runs instead of child
- Thinking code causes compilation error
- Expecting no output from method call
class Base {
public:
void show() { std::cout << "Base"; }
};
class Derived : Base {
public:
void show() { std::cout << "Derived"; }
};
int main() {
Derived d;
d.show();
return 0;
}Solution
Step 1: Verify inheritance syntax
class Derived : Baseis valid syntax; class inheritance defaults to private.Step 2: Trace program execution
Derived d; d.show();callsDerived's publicshow(), printing "Derived". No errors.Final Answer:
No error, code runs fine -> Option CQuick Check:
Private inheritance defaults ok here [OK]
- Assuming default inheritance is public
- Thinking virtual keyword is mandatory here
- Believing derived class cannot have same function name
Car and Bike share common features like start() and stop(), but also have their own unique features. How should you use inheritance in C++ to design this?Solution
Step 1: Identify common features
BothCarandBikesharestart()andstop(), so these belong in a common base class.Step 2: Design inheritance structure
Create a base classVehiclewith common features, then inheritCarandBikefrom it to add unique features.Final Answer:
Create a base class Vehicle with common features, then inherit Car and Bike from it -> Option AQuick Check:
Use base class for shared features [OK]
- Inheriting Car from Bike (wrong 'is-a' relationship)
- Duplicating code instead of reusing via inheritance
- Thinking inheritance requires identical features
Ready to prove it?
Pass the test and this pattern moves unknown
