What if you could write shared code once and magically have many specialized versions without repeating yourself?
Why Base and derived classes in C++? - Purpose & Use Cases
Imagine you are writing a program to manage different types of vehicles: cars, trucks, and motorcycles. You try to write separate code for each vehicle type, repeating similar functions like start, stop, and display details for each one.
This manual approach means you write the same code again and again for each vehicle type. It takes a lot of time, and if you want to change how vehicles start, you must update every single code block. This is slow and easy to make mistakes.
Using base and derived classes lets you write common code once in a base class (like Vehicle). Then, each specific vehicle type (car, truck, motorcycle) can inherit this code and add their own special features. This saves time and keeps your code clean and easy to update.
void startCar() { /* start code */ }
void startTruck() { /* same start code repeated */ }class Vehicle { public: void start() { /* common start code */ } }; class Car : public Vehicle { /* car-specific code */ };
This concept makes it easy to build complex programs with many related objects, sharing common behavior while allowing unique features.
Think of a video game where you have different characters: all can move and attack, but each has special powers. Base and derived classes let you code the shared actions once and customize each character easily.
Base classes hold shared code for related objects.
Derived classes add or change features without repeating code.
This saves time, reduces errors, and makes programs easier to maintain.
Practice
Solution
Step 1: Understand base class role
A base class is designed to hold common features that multiple derived classes can share.Step 2: Compare options
To hold common features shared by derived classes correctly states the purpose. Other options describe derived class behavior or incorrect roles.Final Answer:
To hold common features shared by derived classes -> Option DQuick Check:
Base class = common features [OK]
- Confusing base class with derived class
- Thinking base class cannot have data members
- Assuming base class is only for private data
Car inheriting from base class Vehicle in C++?Solution
Step 1: Recall C++ inheritance syntax
In C++, a derived class inherits from a base class using a colon and access specifier likepublic.Step 2: Check options
class Car : public Vehicle {}; uses correct syntax:class Car : public Vehicle {}. Others use incorrect keywords or omit access specifier.Final Answer:
class Car : public Vehicle {} -> Option BQuick Check:
Inheritance syntax = colon + access specifier [OK]
- Omitting access specifier like public
- Using wrong keywords like inherits or extends
- Forgetting colon before base class name
class Base {
public:
void show() { std::cout << "Base"; }
};
class Derived : public Base {
public:
void show() { std::cout << "Derived"; }
};
int main() {
Derived d;
d.show();
return 0;
}Solution
Step 1: Understand method overriding in derived class
The derived classDerivedhas its ownshow()method which hides the base class method.Step 2: Check which method is called
Callingd.show()on aDerivedobject calls the derived class method, printing "Derived".Final Answer:
Derived -> Option AQuick Check:
Derived method overrides base method [OK]
- Assuming base class method runs without virtual keyword
- Expecting compilation error due to method name clash
- Thinking both outputs print
class Base {
public:
void display() { std::cout << "Base"; }
};
class Derived : public Base {
public:
void display() { std::cout << "Derived"; }
};
int main() {
Base* ptr = new Derived();
ptr->display();
return 0;
}Solution
Step 1: Understand polymorphism with base pointers
Callingdisplay()via a base class pointer calls base method unless it is virtual.Step 2: Check for virtual keyword
The base class methoddisplay()lacksvirtual, soptr->display()calls base version, not derived.Final Answer:
Missing virtual keyword in base class method -> Option AQuick Check:
Virtual needed for polymorphic calls [OK]
- Thinking pointer type is wrong
- Believing derived method runs without virtual
- Assuming static keyword fixes this
class Animal {
public:
virtual std::string sound() { return "Unknown"; }
};
class Dog : public Animal {
public:
std::string sound() override { return "Bark"; }
};
class Cat : public Animal {
public:
std::string sound() override { return "Meow"; }
};
Which code snippet correctly creates a list of animals and prints their sounds?
Solution
Step 1: Understand polymorphism with collections
To preserve derived class behavior, store pointers to base class, not objects by value.Step 2: Analyze options
std::vector animals = {new Dog(), new Cat()}; for(auto a : animals) std::cout << a->sound() << ' '; usesstd::vector<Animal*>with pointers toDogandCat, callingsound()polymorphically.Final Answer:
std::vector<Animal*> animals = {new Dog(), new Cat()}; for(auto a : animals) std::cout << a->sound() << ' '; -> Option CQuick Check:
Use base class pointers for polymorphic containers [OK]
- Storing objects by value causes slicing
- Using wrong container type for polymorphism
- Forgetting to use pointers or references
Ready to prove it?
Pass the test and this pattern moves unknown
