Multiple Inheritance with pure virtual parent - C++ Class

C++ examples for Class:Inheritance

Description

Multiple Inheritance with pure virtual parent

Demo Code

#include <cinttypes>
#include <iostream>

using namespace std;

class Printable/* ww  w .j a  v a2  s.c  om*/
{
public:
    virtual void Print() = 0;
};

class Vehicle
{
public:
    Vehicle() = default;

    virtual int GetNumberOfWheels() const = 0;
};

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

    int GetNumberOfWheels() const override
    {
        return 4;
    }

    void Print() override
    {
        cout << "A car has " << GetNumberOfWheels() << " wheels." << endl;
    }
};
class Motorcycle
    : public Vehicle
    , public Printable
{
public:
    Motorcycle() = default;

    int GetNumberOfWheels() const override
    {
        return 2;
    }

    void Print() override
    {
        cout << "A motorcycle has " << GetNumberOfWheels() << " wheels." << endl;
    }
};

int main(int argc, char* argv[])
{
    Printable* pPrintable{};

    Car myCar{};
    pPrintable = &myCar;
    pPrintable->Print();

    Motorcycle myMotorcycle;
    pPrintable = &myMotorcycle;
    pPrintable->Print();

    return 0;
}

Result


Related Tutorials