0
0
C++programming~20 mins

Why inheritance is used in C++ - See It in Action

Choose your learning style9 modes available
Why inheritance is used
πŸ“– Scenario: Imagine you are creating a program for a vehicle rental company. They have different types of vehicles like cars and trucks. Many vehicles share common features like having wheels and an engine, but some have special features too.
🎯 Goal: You will create a simple example using inheritance in C++ to show how common features can be shared and special features can be added. This will help you understand why inheritance is used.
πŸ“‹ What You'll Learn
Create a base class called Vehicle with a function startEngine()
Create a derived class called Car that inherits from Vehicle
Add a function openTrunk() to the Car class
Create an object of Car and call both startEngine() and openTrunk()
πŸ’‘ Why This Matters
🌍 Real World
Inheritance is used in software to model real-world relationships, like different types of vehicles sharing common features.
πŸ’Ό Career
Understanding inheritance is key for software developers to write clean, reusable, and organized code in many programming languages.
Progress0 / 4 steps
1
Create the base class Vehicle
Write a class called Vehicle with a public function startEngine() that prints "Engine started".
C++
Need a hint?

Use class Vehicle { public: void startEngine() { ... } }; and std::cout to print.

2
Create the derived class Car
Create a class called Car that inherits from Vehicle. Add a public function openTrunk() that prints "Trunk opened".
C++
Need a hint?

Use class Car : public Vehicle and add void openTrunk() inside.

3
Create a Car object and use its functions
Create an object called myCar of type Car. Call myCar.startEngine() and myCar.openTrunk().
C++
Need a hint?

Inside main(), create Car myCar; and call the two functions.

4
Run the program and see the output
Run the program and print the output of calling myCar.startEngine() and myCar.openTrunk().
C++
Need a hint?

Check the console output shows both lines exactly.