Multiple Inheritance

How new classes are created by multiple inheritance and explains their uses. Besides introducing you to creating and destroying objects in multiply-derived classes, virtual base classes are depicted to avoid ambiguity in multiple inheritance.

Multiply-Derived Classes

The multiply-derived class MotorHome

Definition scheme for class MotorHome

class MotorHome : public Car, public Home
{
   private:
     // Additional private members here
   protected:
     // Additional protected members here
   public:
     // Additional public members here
};
A class can contain not just one but several different base classes. In this case the class is derived from multiple base classes in a process known as multiple inheritance.

The Multiply-Derived Class MotorHome

This class Car is used to represent vehicles and the class Home contains characteristic values for an apartment, such as floor space, number and type of rooms, and typical operations, such as building, selling, or renting.
Using these two classes you can then derive the MotorHome class. The opposite page shows the inheritance and definition schemes for the new class. An object of the MotorHome class contains both the members of Car and the members of Home. More specifically, the object contains two base sub-objects of type Car and Home.

Accessibility of Base Classes

Since the MotorHome class has two public base classes, it assumes the public interfaces of both classes. A MotorHome type object not only allows access to the additional public members but to all the public members of the base classes Car and Home.
When defining a multiply-derived class, the accessibility, private, protected, or public, must be defined separately for each base class. The MotorHome class could have the public base class Car and the protected base class Home.
Example:
class MotorHome:public Car,protected Home
{  . . . }; 
If the keyword is omitted, the base class will default to private.
Example:
class MotorHome : public Car, Home
{ . . . }; 
This statement defines the public base class Car and the private base class Home. This makes all the public members in Home private members of the derived class.
In multiple inheritance each public base class establishes an is relationship. This is similar to simple inheritance. If the MotorHome class inherits two public base classes, a motor-home is a special kind of motor vehicle and a special kind of home.

 

Post a Comment

0 Comments