Vehicle Inheritance
Create a base class Vehicle with member variables std::string make, std::string model, and int year. Create two derived classes: Car and Motorcycle. The Car class should have an additional member variable int door_count, and the Motorcycle class will have a member variable bool has_sidecar to indicate if it has a sidecar. You will then instantiate objects of each derived class and print their details.
Hint
Inherit a struct/class from another with this syntax:
class inherited : public base_class {
};
Answer
#include <iostream>
#include <string>
// Base class Vehicle
class Vehicle {
public:
std::string make;
std::string model;
int year;
// Method to print vehicle details
void printDetails() {
std::cout << "Make: " << make << ", Model: " << model << ", Year: " << year << std::endl;
}
};
// Derived class Car
class Car : public Vehicle {
public:
int doors;
// Method to print car details
void printCarDetails() {
// Call the base class method to print common details
Vehicle::printDetails();
std::cout << "Doors: " << doors << std::endl;
}
};
// Derived class Motorcycle
class Motorcycle : public Vehicle {
public:
bool has_sidecar;
// Method to print motorcycle details
void printMotorcycleDetails() {
// Call the base class method to print common details
Vehicle::printDetails();
std::cout << "Has Sidecar: " << (has_sidecar ? "Yes" : "No") << std::endl;
}
};
int main() {
// Instantiate a Car object
Car myCar;
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2021;
myCar.doors = 4;
std::cout << "Car Details:" << std::endl;
myCar.printCarDetails();
// Instantiate a Motorcycle object
Motorcycle myMotorcycle;
myMotorcycle.make = "Harley-Davidson";
myMotorcycle.model = "Sportster";
myMotorcycle.year = 2019;
myMotorcycle.has_sidecar = true;
std::cout << "\nMotorcycle Details:" << std::endl;
myMotorcycle.printMotorcycleDetails();
return 0;
}