In the past articles we saw how we can make a class inherit from another class. This way we could have a new class with features of the base class without explicitly defining them. But what if, we want to have a new class with features form more than one class. In other words, Is it possible for a derived class to inherit multiple base classes (two or more).
Yes it’s possible!
The general from for deriving a class from multiple classes is:
class derived-class:access-specifier base1,access-specifier base2... { ... ... ... };
The following example program illustrates multiple inheritance practically:
// -- INHERITANCE -- // Program to illustrate multiple // inheritance #include<iostream.h> // base class (1) class base1 { protected: int a; public: void showa(){cout<<a<<"\n";} }; // base class (2) class base2 { protected: int b; public: void showb(){cout<<b<<"\n";} }; // derived class // inherits both base1 and base2 // NOTE: Both the base class have // access-specifier class derived:public base1,public base2 { protected: int c; public: void set(int n1,int n2,int n3) { a=n1;b=n2;c=n3; } void show() { cout<<a<<"\n"<<b<<"\n"<<c<<"\n"; } }; void main(void) { derived d; d.set(10,20,30); // access base's members d.showa(); d.showb(); // access derived's member d.show(); }
Related Articles: