fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Base class
  5. class Vehicle {
  6. protected:
  7. int wheels; // Number of wheels
  8. int range; // Range of the vehicle in kilometers
  9.  
  10. public:
  11. // Constructor to initialize Vehicle
  12. Vehicle(int w, int r) : wheels(w), range(r) {}
  13.  
  14. // Function to display Vehicle details
  15. void displayVehicleInfo() {
  16. cout << "Wheels: " << wheels << endl;
  17. cout << "Range: " << range << " km" << endl;
  18. }
  19. };
  20.  
  21. // Derived class: Car
  22. class Car : public Vehicle {
  23. int passengers; // Number of passengers
  24.  
  25. public:
  26. // Constructor to initialize Car
  27. Car(int w, int r, int p) : Vehicle(w, r), passengers(p) {}
  28.  
  29. // Function to display Car details
  30. void displayInfo() {
  31. cout << "Car Information:" << endl;
  32. displayVehicleInfo();
  33. cout << "Passengers: " << passengers << endl;
  34. }
  35. };
  36.  
  37. // Derived class: Truck
  38. class Truck : public Vehicle {
  39. int loadLimit; // Load limit in kilograms
  40.  
  41. public:
  42. // Constructor to initialize Truck
  43. Truck(int w, int r, int l) : Vehicle(w, r), loadLimit(l) {}
  44.  
  45. // Function to display Truck details
  46. void displayInfo() {
  47. cout << "Truck Information:" << endl;
  48. displayVehicleInfo();
  49. cout << "Load Limit: " << loadLimit << " kg" << endl;
  50. }
  51. };
  52.  
  53. int main() {
  54. // Creating a Car object
  55. Car car(4, 500, 5); // 4 wheels, 500 km range, 5 passengers
  56. car.displayInfo();
  57.  
  58. cout << endl;
  59.  
  60. // Creating a Truck object
  61. Truck truck(6, 1000, 15000); // 6 wheels, 1000 km range, 15000 kg load limit
  62. truck.displayInfo();
  63.  
  64. return 0;
  65. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Car Information:
Wheels: 4
Range: 500 km
Passengers: 5

Truck Information:
Wheels: 6
Range: 1000 km
Load Limit: 15000 kg