Vehicle Method Overriding
Create a base class Vehicle with a method start() that outputs "Vehicle is starting". Then, create a derived class Car that overrides the start() method to output "Car is starting". Implement both classes and create an object of Car. Call the start() method to demonstrate method overriding.
Hint
- Ensure the
start()method in theCarclass has the exact same signature as in theVehicleclass.
Answer
#include <iostream>
class Vehicle {
public:
void start() {
std::cout << "Vehicle is starting." << std::endl;
}
};
class Car : public Vehicle {
public:
void start() override {
std::cout << "Car is starting." << std::endl;
}
};
int main() {
Car myCar;
myCar.start(); // Output will be "Car is starting."
return 0;
}