21.3 Virtual Classes

I l @ ve RuBoard

Let's take a look at an auto repair shop. Our shop consists of two rooms. The first is the garage where they repair the cars , and the second is the office where all the paper work is done. Let's design C++ classes for this situation.

Both the garage and the office are rooms, so we have a base class of room and derived classes of garage and office . In C++ our class definitions would be as follows :

 class room {     // ..... }; class garage : public room {     // .... }; class office : public room {     // .... }; 

The two classes garage and office when combined make up the business. The C++ class for this is:

 class repair_shop: public garage, office {    // ... } 

Figure 21-3 illustrates this class structure.

Figure 21-3. Two-room repair shop
figs/c++2_2103.gif

This works well for most repair shops . But what about the small guy that doesn't have enough space for two rooms and must put a desk in the garage and use it as part of his office? In his case, he has one room which is part garage and part office.

Ideally our class diagram should look like Figure 21-4. But we need some way of telling C++, "Don't generate two rooms because we have one room with two uses." This is done by declaring the base class virtual . This keyword tells C++ that the class has multiple uses depending on which part we are taking about.

Figure 21-4. One-room repair shop
figs/c++2_2104.gif
 class room {     // ....  }; class garage_part : virtual public room {     // .... }; class office_part : virtual public room {     // .... }; public small_repair_shop: public office_part, garage_part {    // ... }; 

It should be noted that the classes for the garage section of the business and the office section have to know if they are occupying a room or part of a room.

The class room is used as the base for two derived classes; derived classes cause their base class's constructor to be called to initialize the class. Does this mean that the constructor for room will be called twice? The answer is no. C++ is smart enough to know that room is used twice and to ignore the second initialization.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net