Name : Arslan Ansari
Roll Number : F24BARIN1M01107
Sumbitted to : Prof. Asim Saleem
Subject : Object Oriented Programming (OOPs)
Section : 3M
Code Structure
#include using namespace std;
// Base class
class Vehicle {
protected:
string make;
string model;
int year;
public: // Constructor
Vehicle(string mk, string mdl, int yr)
{ make = mk;
model = mdl;
year = yr; }
// Display method (can be overridden)
virtual void displayDetails() {
cout << "Vehicle Details:" << endl;
cout << "Make: " << make << endl;
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
}
};
// Car class inherits from Vehicle
class Car : public Vehicle {
private: int number_of_doors;
public: Car(string mk, string mdl, int yr, int doors) :
Vehicle(mk, mdl, yr)
{ number_of_doors = doors; }
void displayDetails() override {
Vehicle::displayDetails();
cout << "Number of Doors: " << number_of_doors << endl;
}
};
// Motorcycle class inherits from Vehicle
class Motorcycle : public Vehicle {
private:
bool has_sidecar;
public: Motorcycle(string mk, string mdl, int yr, bool sidecar)
: Vehicle(mk, mdl, yr) {
has_sidecar = sidecar; }
void displayDetails() override {
Vehicle::displayDetails();
cout << "Has Sidecar: " << (has_sidecar ? "Yes" : "No") << endl;
}
};
// Truck class inherits from Vehicle
class Truck : public Vehicle {
private:
float load_capacity; // in tons
public: Truck(string mk, string mdl, int yr, float capacity)
: Vehicle(mk, mdl, yr) { load_capacity = capacity; }
void displayDetails() override {
Vehicle::displayDetails();
cout << "Load Capacity: " << load_capacity << " tons" << endl;
}
};
int main() {
Car myCar ("Toyota", "Corolla", 2022, 4);
Motorcycle myBike("Harley-Davidson", "Iron 883", 2021, false);
Truck myTruck("Volvo", "FH16", 2020, 20.5);
// Displaying details
cout << "Car Info:" << endl;
myCar.displayDetails();
cout << "----------------------" << endl;
cout << "Motorcycle Info:" << endl;
myBike.displayDetails();
cout << "----------------------" << endl;
cout << "Truck Info:" << endl;
myTruck.displayDetails();
cout << "----------------------" << endl;
return 0;
How Inheritance Helps in This Scenario
Inheritance promotes code reuse, modularity, and extensibility:
• The Vehicle class holds common properties and methods for all vehicle types
(make, model, year, and displayDetails()).
• Car, Motorcycle, and Truck extend the base class to avoid duplicating shared
logic.
• Each subclass overrides the displayDetails() method to include specific
details while still using the base structure.
Explanation: Method Overriding
• In the base class Vehicle, displayDetails() prints basic info.
• Each subclass overrides displayDetails() to:
o Call super().displayDetails() (use the base implementation).
o Append subclass-specific information.
This allows consistent behavior (displayDetails()) across all vehicle types, while
showing different details — this is polymorphism in action.
<---------------------------------------------------------------->