0
0
C++programming~30 mins

Base and derived classes in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Base and Derived Classes in C++
πŸ“– Scenario: You are creating a simple program to represent vehicles. You want to show how a basic vehicle can be extended to a specific type of vehicle, like a car, using base and derived classes.
🎯 Goal: Build a C++ program that defines a base class Vehicle and a derived class Car. You will add properties and methods to both classes and display information about a car.
πŸ“‹ What You'll Learn
Create a base class named Vehicle with a public string variable brand.
Create a derived class named Car that inherits from Vehicle and has a public string variable model.
Add a public method display() in Car that prints the brand and model.
Create an object of Car, set its brand and model, and call display().
πŸ’‘ Why This Matters
🌍 Real World
Base and derived classes help organize code when many objects share common features but also have unique details, like different types of vehicles.
πŸ’Ό Career
Understanding inheritance is key for software development jobs that involve object-oriented programming, making code easier to maintain and extend.
Progress0 / 4 steps
1
Create the base class Vehicle
Write a base class called Vehicle with a public string variable named brand.
C++
Need a hint?

Use class Vehicle { public: std::string brand; }; to define the base class.

2
Create the derived class Car
Create a derived class called Car that inherits from Vehicle. Add a public string variable named model.
C++
Need a hint?

Use class Car : public Vehicle { public: std::string model; }; to create the derived class.

3
Add display() method to Car
Add a public method named display() inside the Car class. This method should print the brand and model separated by a space.
C++
Need a hint?

Define void display() { std::cout << brand << " " << model << std::endl; } inside Car.

4
Create Car object and display info
In the main() function, create an object named myCar of type Car. Set myCar.brand to "Toyota" and myCar.model to "Corolla". Then call myCar.display() to print the brand and model.
C++
Need a hint?

Create Car myCar;, set myCar.brand = "Toyota"; and myCar.model = "Corolla";, then call myCar.display();.