Home > Development > C++ Multiple Inheritance Examples and Issues

C++ Multiple Inheritance Examples and Issues


Diving straight in with some code…

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

class Dog{
public:
    void Bark();
};

class Bird{
public:
    void Chirp();
};

void Dog::Bark(){
    cout << "Bark" << endl;
}

void Bird::Chirp(){
    cout << "Chirp" << endl;
}

class DogBird : public Dog, public Bird{

};

class B1{
public:
    virtual void Print();
};

class B2{
public:
    virtual void Print();
};

void B1::Print(){
    cout << "B1 Print" << endl;
}

void B2::Print(){
    cout << "B1 Print" << endl;
}

class B3 : public B1, public B2{

};

int main(int argc, char *argv[])
{
    DogBird* c = new DogBird();
    c->Bark();
    c->Chirp();
    delete c;

    B3* b = new B3();
    b->B1::Print();
}

You can see two class Dog and Bird declared initially. Then DogBird inherits from both. The we can see both the bark and chirp methods are available in the derived class DogBird. Pretty easy.
So were the pain come in is when both parent classes have a method with the same name, see the B1 and B3 classes. We B3 inherits this and you call print which one should it choose?? The compiler only get un happy when you actually make a call to this which can also be a trap. If you see the b->B1::Print() statement this means use the print from B! class. This is horrible.

Rule of thumb if you own the classes i.e you wrote them change the names so there distinct, much easier and less error prone, otherwise if its a third party class, live with it.

Blair..

Advertisements
Categories: Development Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: