The virtual keyword allows you to create methods that can be overridden by derived classes. - C++ Class

C++ examples for Class:Inheritance

Introduction

Accessing Virtual Methods through a Base Pointer

Demo Code

#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;
}

Result


Related Tutorials