Multiple inheritance example in C++

By: Norman Chap Emailed: 1643 times Printed: 2112 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. To derive from more than the base class, you separate each base class by commas in the class designation. Listing below illustrates how to declare Pegasus so that it derives from both Horses and Birds. The program then adds Pegasus objects to both types of lists.

Multiple inheritance.

1:     // Multiple inheritance.
2:     // Multiple Inheritance
3:
4:     #include <iostream.h>
5:
6:     class Horse
7:     {
8:     public:
9:        Horse() { cout << "Horse constructor... "; }
10:       virtual ~Horse() { cout << "Horse destructor... "; }
11:       virtual void Whinny() const { cout << "Whinny!... "; }
12:    private:
13:       int itsAge;
14:    };
15:
16:    class Bird
17:    {
18:    public:
19:       Bird() { cout << "Bird constructor... "; }
20:       virtual ~Bird() { cout << "Bird destructor... "; }
21:       virtual void Chirp() const { cout << "Chirp... ";  }
22:       virtual void Fly() const 
23:       { 
24:          cout << "I can fly! I can fly! I can fly! "; 
25:       }
26:    private:
27:       int itsWeight;
28:    };
29:
30:    class Pegasus : public Horse, public Bird
31:    {
32:    public:
33:       void Chirp() const { Whinny(); }
34:       Pegasus() { cout << "Pegasus constructor... "; }
35:       ~Pegasus() { cout << "Pegasus destructor...  "; }
36:    };
37:
38:    const int MagicNumber = 2;
39:    int main()
40:    {
41:       Horse* Ranch[MagicNumber];
42:       Bird* Aviary[MagicNumber];
43:       Horse * pHorse;
44:       Bird * pBird; 
45:       int choice,i;
46:       for (i=0; i<MagicNumber; i++)
47:       {
48:          cout << "\n(1)Horse (2)Pegasus: ";
49:          cin >> choice;
50:          if (choice == 2)
51:             pHorse = new Pegasus;
52:          else
53:             pHorse = new Horse;
54:          Ranch[i] = pHorse;
55:       }
56:       for (i=0; i<MagicNumber; i++)
57:       {
58:          cout << "\n(1)Bird (2)Pegasus: ";
59:          cin >> choice;
60:          if (choice == 2)
61:             pBird = new Pegasus; 
62:          else
63:             pBird = new Bird;
64:          Aviary[i] = pBird;
65:       }
66:
67:       cout << "\n";
68:       for (i=0; i<MagicNumber; i++)
69:       {
70:          cout << "\nRanch[" << i << "]: " ;
71:          Ranch[i]->Whinny();
72:          delete Ranch[i];
73:       }
74:
75:       for (i=0; i<MagicNumber; i++)
76:       {
77:          cout << "\nAviary[" << i << "]: " ;
78:          Aviary[i]->Chirp();
79:          Aviary[i]->Fly();
80:          delete Aviary[i];
81:       }
82:     return 0;
83: }

Output: (1)Horse (2)Pegasus: 1
Horse constructor...
(1)Horse (2)Pegasus: 2
Horse constructor... Bird constructor... Pegasus constructor...
(1)Bird (2)Pegasus: 1
Bird constructor...
(1)Bird (2)Pegasus: 2
Horse constructor... Bird constructor... Pegasus constructor...

Ranch[0]: Whinny!... Horse destructor...
Ranch[1]: Whinny!... Pegasus destructor...  Bird destructor... Horse destructor...
Aviary[0]: Chirp... I can fly! I can fly! I can fly! Bird destructor...
Aviary[1]: Whinny!... I can fly! I can fly! I can fly! 
Pegasus destructor... Bird destructor... Horse destructor...
Aviary[0]: Chirp... I can fly! 
I can fly! I can fly! Bird destructor...
Aviary[1]: Whinny!... I can fly! I can fly! I can fly! 
Pegasus destructor.. Bird destructor... Horse destructor... 

Analysis: On lines 6-14, a Horse class is declared. The constructor and destructor print out a message, and the Whinny() method prints the word Whinny!

On lines 16-25, a Bird class is declared. In addition to its constructor and destructor, this class has two methods: Chirp() and Fly(), both of which print identifying messages. In a real program these might, for example, activate the speaker or generate animated images.

Finally, on lines 30-36, the class Pegasus is declared. It derives both from Horse and from Bird. The Pegasus class overrides the Chirp() method to call the Whinny() method, which it inherits from Horse.

Two lists are created, a Ranch with pointers to Horse on line 41, and an Aviary with pointers to Bird on line 42. On lines 46-55, Horse and Pegasus objects are added to the Ranch. On lines 56-65, Bird and Pegasus objects are added to the Aviary.

Invocations of the virtual methods on both the Bird pointers and the Horse pointers do the right things for Pegasus objects. For example, on line 78 the members of the Aviary array are used to call Chirp() on the objects to which they point. The Bird class declares this to be a virtual method, so the right function is called for each object.

Note that each time a Pegasus object is created, the output reflects that both the Bird part and the Horse part of the Pegasus object is also created. When a Pegasus object is destroyed, the Bird and Horse parts are destroyed as well, thanks to the destructors being made virtual.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Norman Chap
The break Statement example in Java
Stored Procedures example in SQL
JDBC and Tomcat context settings
File read and write - sample program in C
Pointers and Function Arguments in C
Writing the first Struts application
goto and labels in C
External Variables and Scope in C
Multiple inheritance example in C++
qsort() sample program in C++
Image and ImageItem sample program in J2ME
SimpleDateFormat sample program in Java
Observable class and the sample program in Java

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using Comments in a C++ Program
Using cout.width() in C++
Dot (.) vs Arrow (->) to access data members in C++
Calculate average using Two-Dimensional Array in C++
Tutorial on Inline Implementation in C++
assert() example program in C++
Programming errors a compiler will detect in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Difference between Procedural, Structured, and Object-Oriented Programming
C++ Destructors Versus Java Finalization
strcat() and strncat() sample program in C++
cin.ignore() in C++
Compute the square root of the sum of the squares of an array in C++
Operator Precedence in C++
Most Emailed Articles (in C++)
Public versus Private members in C++
The indirection operator (*) - dereference operator.
const Pointers in C++
Returning values from a function in C++
while (1) Loops in C++
Sorting an array of Strings in C++
Using Comments in a C++ Program
Specifying default values to function parameters in C++
continue and break statements in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Calculating total based on the given quantity and price in C++
Demonstrating global and local variables in C++
while Loops in C++
Manipulating Data by Using Pointers