C++ examples for Class:Inheritance
Accessing Virtual Methods through a Base Pointer
#include <cinttypes> #include <iostream> using namespace std; class Vehicle/*from w ww. j a v a 2 s. c om*/ { public: Vehicle() = default; virtual int GetNumberOfWheels() const { return 2; } }; class Car : public Vehicle { public: Car() = default; int GetNumberOfWheels() const override { return 4; } }; class Motorcycle : public Vehicle { public: Motorcycle() = default; }; int main(int argc, char* argv[]) { Vehicle* pVehicle{}; Vehicle myVehicle{}; pVehicle = &myVehicle; cout << "A vehicle has " << pVehicle->GetNumberOfWheels() << " wheels." << endl; Car myCar{}; pVehicle = &myCar; cout << "A car has " << pVehicle->GetNumberOfWheels() << " wheels." << endl; Motorcycle myMotorcycle; pVehicle = &myMotorcycle; cout << "A motorcycle has " << pVehicle->GetNumberOfWheels() << " wheels." << endl; return 0; }