0
0
C++programming~30 mins

Pure virtual functions in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Pure Virtual Functions in C++
πŸ“– Scenario: Imagine you are designing a simple program for different types of vehicles. Each vehicle can start its engine, but the way it starts might differ. We want to create a base class that forces all vehicle types to define their own way to start the engine.
🎯 Goal: You will create a base class with a pure virtual function and then create derived classes that implement this function. Finally, you will create objects of the derived classes and call their start engine methods.
πŸ“‹ What You'll Learn
Create a base class called Vehicle with a pure virtual function startEngine().
Create two derived classes called Car and Motorcycle that override startEngine().
Create objects of Car and Motorcycle and call their startEngine() methods.
Print the output of each startEngine() call.
πŸ’‘ Why This Matters
🌍 Real World
Pure virtual functions are used in software design to create interfaces or abstract base classes that define common behavior but require specific implementations in derived classes.
πŸ’Ό Career
Understanding pure virtual functions is essential for C++ developers working on large projects, especially in areas like game development, system programming, and software architecture where polymorphism and abstraction are key.
Progress0 / 4 steps
1
Create the base class with a pure virtual function
Write a class called Vehicle with a public pure virtual function startEngine() that returns void.
C++
Need a hint?

A pure virtual function is declared by adding = 0 at the end of the function declaration inside the class.

2
Create derived classes that override the pure virtual function
Create two classes called Car and Motorcycle that publicly inherit from Vehicle. Override the startEngine() function in both classes to print "Car engine started" and "Motorcycle engine started" respectively.
C++
Need a hint?

Use override keyword to make sure you are overriding the base class function.

3
Create objects of derived classes and call startEngine
In the main() function, create an object called myCar of type Car and an object called myMotorcycle of type Motorcycle. Call the startEngine() method on both objects.
C++
Need a hint?

Create objects and call their startEngine() methods using dot notation.

4
Print the output of the startEngine calls
Run the program and print the output of calling startEngine() on myCar and myMotorcycle. The output should show the engine start messages for both vehicles.
C++
Need a hint?

When you run the program, the messages from the startEngine() calls will appear on the screen.