Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
B.Eckel - Thinking in C++, Vol.2, 2nd edition.pdf
Скачиваний:
50
Добавлен:
08.05.2013
Размер:
2.09 Mб
Скачать

by a space to enable parsing) to allow the read( ) function to allocate the correct amount of storage.

When you have subobjects that have read( ) and write( ) member functions, all you need to do is call those functions in the new read( ) and write( ) functions. This is followed by direct storage of the members in the base class.

People have gone to great lengths to automate persistence, for example, by creating modified preprocessors to support a “persistent” keyword to be applied when defining a class. One can imagine a more elegant approach than the one shown here for implementing persistence, but it has the advantage that it works under all implementations of C++, doesn’t require special language extensions, and is relatively bulletproof.

Avoiding MI

The need for multiple inheritance in Persist2.cpp is contrived, based on the concept that you don’t have control of some of the code in the project. Upon examination of the example, you can see that MI can be easily avoided by using member objects of type Data, and putting the virtual read( )and write( ) members inside Data or WData1 and WData2 rather than in a separate class. There are many situations like this one where multiple inheritance may be avoided; the language feature is included for unusual, special-case situations that would otherwise be difficult or impossible to handle. But when the question of whether to use multiple inheritance comes up, you should ask two questions:

1.Do I need to show the public interfaces of both these classes, or could one class be embedded with some of its interface produced with member functions in the new class?

2.Do I need to upcast to both of the base classes? (This applies when you have more than two base classes, of course.)

If you can’t answer “no” to both questions, you can avoid using MI and should probably do so.

One situation to watch for is when one class only needs to be upcast as a function argument. In that case, the class can be embedded and an automatic type conversion operator provided in your new class to produce a reference to the embedded object. Any time you use an object of your new class as an argument to a function that expects the embedded object, the type conversion operator is used. However, type conversion can’t be used for normal member selection; that requires inheritance.

Mixin types

Rodents & pets(play)

Chapter 15: Multiple Inheritance

362

interfaces in general

Repairing an interface

One of the best arguments for multiple inheritance involves code that’s out of your control. Suppose you’ve acquired a library that consists of a header file and compiled member functions, but no source code for member functions. This library is a class hierarchy with virtual functions, and it contains some global functions that take pointers to the base class of the library; that is, it uses the library objects polymorphically. Now suppose you build an application around this library, and write your own code that uses the base class polymorphically.

Later in the development of the project or sometime during its maintenance, you discover that the base-class interface provided by the vendor is incomplete: A function may be nonvirtual and you need it to be virtual, or a virtual function is completely missing in the interface, but essential to the solution of your problem. If you had the source code, you could go back and put it in. But you don’t, and you have a lot of existing code that depends on the original interface. Here, multiple inheritance is the perfect solution.

For example, here’s the header file for a library you acquire:

//: C06:Vendor.h

//Vendor-supplied class header

//You only get this & the compiled Vendor.obj #ifndef VENDOR_H

#define VENDOR_H

class Vendor { public:

virtual void v() const; void f() const; ~Vendor();

};

class Vendor1 : public Vendor { public:

void v() const; void f() const; ~Vendor1();

};

void A(const Vendor&); void B(const Vendor&); // Etc.

Chapter 15: Multiple Inheritance

363

#endif // VENDOR_H ///:~

Assume the library is much bigger, with more derived classes and a larger interface. Notice that it also includes the functions A( ) and B( ), which take a base pointer and treat it polymorphically. Here’s the implementation file for the library:

//: C06:Vendor.cpp {O}

//Implementation of VENDOR.H

//This is compiled and unavailable to you #include "Vendor.h"

#include <fstream> using namespace std;

extern ofstream out; // For trace info

void Vendor::v() const { out << "Vendor::v()\n";

}

void Vendor::f() const { out << "Vendor::f()\n";

}

Vendor::~Vendor() {

out << "~Vendor()\n";

}

void Vendor1::v() const { out << "Vendor1::v()\n";

}

void Vendor1::f() const { out << "Vendor1::f()\n";

}

Vendor1::~Vendor1() { out << "~Vendor1()\n";

}

void A(const Vendor& V) { // ...

V.v();

V.f();

//..

Chapter 15: Multiple Inheritance

364

}

void B(const Vendor& V) { // ...

V.v();

V.f();

//.. } ///:~

In your project, this source code is unavailable to you. Instead, you get a compiled file as Vendor.obj or Vendor.lib (or the equivalent for your system).

The problem occurs in the use of this library. First, the destructor isn’t virtual. This is actually a design error on the part of the library creator. In addition, f( ) was not made virtual; assume the library creator decided it wouldn’t need to be. And you discover that the interface to the base class is missing a function essential to the solution of your problem. Also suppose you’ve already written a fair amount of code using the existing interface (not to mention the functions A( ) and B( ), which are out of your control), and you don’t want to change it.

To repair the problem, create your own class interface and multiply inherit a new set of derived classes from your interface and from the existing classes:

//: C06:Paste.cpp //{L} Vendor

// Fixing a mess with MI #include "Vendor.h" #include <fstream>

using namespace std;

ofstream out("paste.out");

class MyBase { // Repair Vendor interface public:

virtual void v() const = 0; virtual void f() const = 0; // New interface function: virtual void g() const = 0;

virtual ~MyBase() { out << "~MyBase()\n"; }

};

class Paste1 : public MyBase, public Vendor1 { public:

void v() const {

out << "Paste1::v()\n"; Vendor1::v();

Chapter 15: Multiple Inheritance

365

}

void f() const {

out << "Paste1::f()\n"; Vendor1::f();

}

void g() const {

out << "Paste1::g()\n";

}

~Paste1() { out << "~Paste1()\n"; }

};

int main() {

Paste1& p1p = *new Paste1; MyBase& mp = p1p; // Upcast out << "calling f()\n"; mp.f(); // Right behavior out << "calling g()\n"; mp.g(); // New behavior

out << "calling A(p1p)\n"; A(p1p); // Same old behavior out << "calling B(p1p)\n"; B(p1p); // Same old behavior out << "delete mp\n";

// Deleting a reference to a heap object: delete &mp; // Right behavior

} ///:~

In MyBase (which does not use MI), both f( ) and the destructor are now virtual, and a new virtual function g( ) has been added to the interface. Now each of the derived classes in the original library must be recreated, mixing in the new interface with MI. The functions Paste1::v( ) and Paste1::f( )need to call only the original base-class versions of their functions. But now, if you upcast to MyBase as in main( )

MyBase* mp = p1p; // Upcast

any function calls made through mp will be polymorphic, including delete. Also, the new interface function g( ) can be called through mp. Here’s the output of the program:

calling f() Paste1::f() Vendor1::f() calling g() Paste1::g() calling A(p1p) Paste1::v()

Chapter 15: Multiple Inheritance

366

Соседние файлы в предмете Численные методы
  • #
    08.05.20133.99 Mб22A.Menezes, P.van Oorschot,S.Vanstone - HANDBOOK OF APPLIED CRYPTOGRAPHY.djvu
  • #
  • #
    08.05.20135.91 Mб24B.Eckel - Thinking in Java, 3rd edition (beta).pdf
  • #
  • #
    08.05.20136.09 Mб17D.MacKay - Information Theory, Inference, and Learning Algorithms.djvu
  • #
    08.05.20133.85 Mб15DIGITAL Visual Fortran ver.5.0 - Programmers Guide to Fortran.djvu
  • #
    08.05.20131.84 Mб12E.A.Lee, P.Varaiya - Structure and Interpretation of Signals and Systems.djvu