Inheriting from a Class - C++ Class

C++ examples for Class:Inheritance

Description

Inheriting from a Class

Demo Code

#include <cinttypes>
#include <iostream>

using namespace std;

class Vehicle//from  w  ww .  j  ava2 s.co m
{
private:
    int m_NumberOfWheels{};
public:
    Vehicle(int numberOfWheels)
        : m_NumberOfWheels{ numberOfWheels }
    {

    }

    int GetNumberOfWheels() const
    {
        return m_NumberOfWheels;
    }
};

class Car : public Vehicle
{
public:
    Car()
        : Vehicle(4)
    {

    }
};

class Motorcycle : public Vehicle
{
public:
    Motorcycle()
        : Vehicle(2)
    {

    }
};

int main(int argc, char* argv[])
{
    Car myCar{};
    cout << "A car has " << myCar.GetNumberOfWheels() << " wheels." << endl;

    Motorcycle myMotorcycle;
    cout << "A motorcycle has " << myMotorcycle.GetNumberOfWheels() << " wheels." << endl;

    return 0;
}

Result


Related Tutorials