www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C++ Tutorial - Lesson 31: Multiple Inheritance

Introduction

by John Kopp

Support this site at no cost to you

Introduction
Welcome to EasyCPlusPlus.com's free tutorial on C++ programming. This lesson covers multiple inheritance. In C++, a class may have multiple base classes. That is, it may inherit the members and methods of multiple base classes. As an example of this, I will walk you through some recent design I have done for my top secret Jet-Car project. Over the last year, tired of both endless construction on the roads and increased time to pass through tightened airport security, I have embarked on producing the only reasonable solution to my commuting nightmares, a homemade Jet-Car.

As I started on my Jet-Car design, I began with two existing classes I developed for earlier lessons, the Vehicle and Car classes.

#include <iostream>
using namespace std;

class Vehicle {
public:
    Vehicle() {cout << "Vehicle Constructor" << endl;}
    virtual ~Vehicle() {cout << "Vehicle Destructor" << endl;}

    virtual void accelerate() const {cout << "Vehicle Accelerating" << endl;}

    void setAcceleration(double a) {acceleration = a;}
    double getAcceleration() const {return acceleration;}

private:
double acceleration;
};

class Car: public Vehicle {
public:
    Car() {cout << "Car Constructor" << endl;}
    virtual ~Car() {cout << "Car Destructor" << endl;}

    virtual void accelerate() const {cout << "Car Accelerating" << endl;}
    void drive() const {cout << "Car Driving" << endl;}

private:
    // Car inherits acceleration accessors, member
};

int main() {

    Car myCar;

    myCar.setAcceleration(9.81);
        //One "G"

    cout << "Accelerating at " << myCar.getAcceleration() << " m/(s*s)";
    cout << endl;

    myCar.accelerate();
    myCar.drive();

}

Previous Page       Next Page