22.3.1.  Multiple Inheritance Syntax

[ fromfile: multiple-inheritance.xml id: multinsimpleex ]

The example in this section demonstrates multiple inheritance syntax and usage.

Figure 22.2.  Window and ScreenRegion

Window and ScreenRegion

The two base classes shown in Figure 22.2, Rectangle and ScreenRegion, each have particular roles to play on the screen. One class is concerned with shape and location, whereas the other is concerned with color and visibility characteristics. A Window must be a Rectangle and a ScreenRegion. They are defined in Example 22.7.

Example 22.7. src/multinheritance/window.h

[ . . . . ]

class Rectangle {
 public:
    Rectangle( Const Point& ul, int length, int width);
    Rectangle( const Rectangle& r) ;
    void move (const Point &newpoint);
 private:
    Point m_UpperLeft;
    int m_Length, m_Width;
};

class ScreenRegion {
 public:
    ScreenRegion( Color c=White);
    ScreenRegion (const ScreenRegion& sr);
    virtual color Fill( Color newColor) ;
    void show();
    void hide();
 private:
    Color m_Color;
    // other members...
    
};

class Window: public Rectangle, public ScreenRegion {
 public:
    Window( const Point& ul, int len, int wid, Color c)
        : Rectangle(ul, len, wid), ScreenRegion(c) {} 1

    Window( const Rectangle& rect, const ScreenRegion& sr)
        : Rectangle(rect), ScreenRegion(sr) {}        2
             
    // Other useful member functions ...
};

1

Use base class ctors.

2

Use base class copy ctors.


There are some syntax items in the classHead of Window that deserve some attention.

Example 22.8 has some client code for the Window class.

Example 22.8. src/multinheritance/window.cpp

#include "window.h"

int main() {
    Window w(Point(15,99), 50, 100, Color(22));
    w.show();            1
    w.move (Point(4,6)); 2
    return 0;
 }

1

Calls ScreenRegion::show();

2

Calls Rectangle::move();


Order of Member Initialization

Default Initialization or assignment proceeds member-by-member in the order that data members are declared in the class definition: base classes first, followed by derived class members.