Creating Interfaces, Creating Pure Virtual Methods - C++ Class

C++ examples for Class:Virtual Function

Description

Creating Interfaces, Creating Pure Virtual Methods

Demo Code

#include <cinttypes>
#include <iostream>

using namespace std;

class Vehicle// w ww . ja va  2 s . c  o  m
{
public:
    Vehicle() = default;

    virtual int GetNumberOfWheels() const = 0;
};

class Car : public Vehicle
{
public:
    Car() = default;

    int GetNumberOfWheels() const override
    {
        return 4;
    }
};

class Motorcycle : public Vehicle
{
public:
    Motorcycle() = default;
    int GetNumberOfWheels() const override
    {
        return 2;
    }
};

int main(int argc, char* argv[])
{
    Vehicle* pVehicle{};

    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