#include <iostream>
// Base class vehicle with virtual function for sound
class vehicle {//base class is needed for (polymorphism)
public:
virtual void sound() = 0; // Pure virtual function (abstract class)
};
// The 'car' class demonstrates both encapsulation and abstraction
class car : public vehicle {
private:
// Private members (encapsulation)
int fuel;
int speed;
public:
// Constructor to initialize speed and fuel
car(int sp, int fl);
// Public methods (abstraction)
int getspeed(); // Getter for speed
int getfuel(); // Getter for fuel
void drive(int a); // Method to drive the car
// Overriding sound method
void sound() override;
};
// Derived class bike from base class vehicle
class bike : public vehicle {
public:
// Overriding sound method
void sound() override;
};
// Constructor definition
car::car(int sp, int fl) : speed(sp), fuel(fl) {}
// Method to get the current speed
int car::getspeed() {
return speed;
}
// Method to get the current fuel
int car::getfuel() {
return fuel;
}
// Method to drive the car
void car::drive(int a) {
speed += a; // Increase the speed
fuel -= a; // Decrease the fuel (since driving consumes fuel)
if (fuel < 0) fuel = 0; // Ensure fuel doesn't go negative
}
// Overridden sound method for car
void car::sound() {
std::cout << "dru dru" << std::endl;
}
// Overridden sound method for bike
void bike::sound() {
std::cout << "bur bur" << std::endl;
}
int main() {
// Create car and bike objects
car c1(5, 100); // Car with speed 5 and fuel 100
bike b1;
// Polymorphism via base class pointer// pointer is needed for polymorphism
vehicle* v1 = &c1; // Point to car
vehicle* v2 = &b1; // Point to bike
// Drive the car
c1.drive(50);
// Output the current speed and fuel level of the car
std::cout << "Car speed: " << c1.getspeed() << std::endl;
std::cout << "Car fuel: " << c1.getfuel() << std::endl;
// Call the sound method using polymorphism
v1->sound(); // Calls car's sound method
v2->sound(); // Calls bike's sound method
}
To embed this project on your website, copy the following code and paste it into your website's HTML: