Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
1715
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 10

void lessPresumptuous(Super* inSuper)

{

Sub* mySub = dynamic_cast<Sub*>(inSuper);

if (mySub != NULL) {

// Proceed to access Sub methods on mySub.

}

}

If a dynamic cast fails on a pointer, as above, the pointer’s value will be NULL instead of pointing to nonsensical data. If a dynamic_cast fails on an object reference, a std::bad_cast exception will be thrown. For more on casts, see Chapter 12. For more on exceptions, see Chapter 15.

Use downcasting only when necessary and be sure to use a dynamic cast.

Inheritance for Polymorphism

Now that you understand the relationship between a subclass and its parent, you can use inheritance in its most powerful scenario — polymorphism. As you learned in Chapter 3, polymorphism allows you to use objects with a common parent class interchangeably, and to use objects in place of their parents.

Return of the Spreadsheet

Chapters 8 and 9 used a spreadsheet program as an example of an application that lends itself to an object-oriented design. As you may recall, a SpreadsheetCell represented a single element of data. That element could be either a double or a string. A simplified class definition for SpreadsheetCell follows. Note that a cell can be set either as a double or a string. The current value of the cell, however, is always returned as a string for this example.

class SpreadsheetCell

{

public:

SpreadsheetCell();

virtual void set(double inDouble);

virtual void set(const std::string& inString); virtual std::string getString();

protected:

static std::string doubleToString(double inValue);

static double stringToDouble(const std::string& inString);

double mValue; std::string mString;

};

The preceding SpreadsheetCell class seems to be having an identity crisis — sometimes a cell represents a double, sometimes a string. Sometimes it has to convert between these formats. To achieve this duality, the class needs to store both values even though a given cell should only be able to contain a

240

Discovering Inheritance Techniques

single value. Worse still, what if additional types of cells are needed, such as a formula cell or a date cell? The SpreadsheetCell class would grow dramatically to support all of these data types and the conversions between them.

Designing the Polymorphic Spreadsheet Cell

The SpreadsheetCell class is screaming out for a hierarchical makeover. A reasonable approach would be to narrow the scope of the SpreadsheetCell to cover only strings, perhaps renaming it StringSpreadsheetCell in the process. To handle doubles, a second class, DoubleSpreadsheetCell, would inherit from the StringSpreadsheetCell and provide functionality specific to its own format. Figure 10-5 illustrates such a design. This approach models inheritance for reuse since the

DoubleSpreadsheetCell would only be subclassing StringSpreadsheetCell to make use of some of its built-in functionality.

StringSpreadsheetCell

DoubleSpreadsheetCell

Figure 10-5

If you were to implement the design shown in Figure 10-5, you might discover that the subclass would override most, if not all, of the functionality of the base class. Since doubles are treated differently from strings in almost all cases, the relationship may not be quite as it was originally understood. Yet, there clearly is a relationship between a cell containing strings and a cell containing doubles. Rather than use the model in Figure 10-5, which implies that somehow a DoubleSpreadsheetCell “is-a” StringSpreadsheetCell, a better design would make these classes peers with a common parent, SpreadsheetCell. Such a design is shown in Figure 10-6.

SpreadsheetCell

StringSpreadsheetCell DoubleSpreadsheetCell

Figure 10-6

The design in Figure 10-6 shows a polymorphic approach to the SpreadsheetCell hierarchy. Since

DoubleSpreadsheetCell and StringSpreadsheetCell both inherit from a common parent,

SpreadsheetCell, they are interchangeable in the view of other code. In practical terms, that means:

Both subclasses support the same interface (set of methods) defined by the base class

Code that makes use of SpreadsheetCell objects can call any method in the interface without even knowing whether the cell is a DoubleSpreadsheetCell or a StringSpreadsheetCell

Through the magic of virtual methods, the appropriate version of every method in the interface will be called depending on the class of the object

Other data structures, such as the Spreadsheet class described in Chapter 9, can contain a collection of multityped cells by referring to the parent type

241

Chapter 10

The Spreadsheet Cell Base Class

Since all spreadsheet cells are subclasses of the SpreadsheetCell base class, it is probably a good idea to write that class first. When designing a base class, you need to consider how the subclasses relate to each other. From this information, you can derive the commonality that will go inside the parent class. For example, string cells and double cells are similar in that they both contain a single piece of data. Since the data is coming from the user and will be displayed back to the user, the value is set as a string and retrieved as a string. These behaviors are the shared functionality that will make up the base class.

A First Attempt

The SpreadsheetCell base class is responsible for defining the behaviors that all SpreadsheetCell subclasses will support. In our simple example, all cells need to be able to set their value as a string. All cells also need to be able to return their current value as a string. The base class definition, therefore, declares these methods.

class SpreadsheetCell

{

public:

SpreadsheetCell();

virtual ~SpreadsheetCell();

virtual void set(const std::string& inString);

virtual std::string getString() const;

};

When you start writing the .cpp file for this class, you very quickly run into a problem. Since the base class of spreadsheet cell contains neither a double nor a string, how can you implement it? More generally, how do you write a parent class that declares the behaviors that are supported by subclasses without actually defining the implementation of those behaviors?

One possible approach is to implement “do nothing” functionality for those behaviors. For example, calling the set() method on the SpreadsheetCell base class will have no effect because the base class has nothing to set. This approach still doesn’t feel right, however. Ideally, there should never be an object that is an instance of the base class. Calling set() should always have an effect because it should always be called on either a DoubleSpreadsheetCell or a StringSpreadsheetCell. A good solution will enforce this constraint.

Pure Virtual Methods and Abstract Base Classes

Pure virtual methods are methods that are explicitly undefined in the class definition. By making a method pure virtual, you are telling the compiler that no definition for the method exists in the current class. Thus, the class is said to be abstract because no other code will be able to instantiate it. The compiler enforces the fact that if a class contains one or more pure virtual methods, it can never be used by itself to construct an object.

The syntax for a pure virtual method is shown below. Simply set the method equal to zero in the class definition. No code needs to be written in the .cpp file.

242

Discovering Inheritance Techniques

class SpreadsheetCell

{

public:

SpreadsheetCell();

virtual ~SpreadsheetCell();

virtual void set(const std::string& inString) = 0;

virtual std::string getString() const = 0;

};

Now that the base class is an abstract class, it is impossible to create a SpreadsheetCell object. The following code will not compile, and will give an error such as Cannot declare object of type ‘SpreadsheetCell’ because one or more virtual functions are abstract.

int main(int argc, char** argv)

{

SpreadsheetCell cell; // BUG! Attempts to create instance of an abstract class

}

An abstract class provides a way to prevent other code from instantiating an object directly, as opposed to one of its subclasses.

Base Class Source Code

There is not much code required for SpreadsheetCell.cpp. As the class was defined, most of the methods are pure virtual — there is no definition to give. All that is left is the type conversion method and the constructor and destructor. For this example, the constructor and destructor are implemented just as a placeholder in case initialization and destruction tasks need to happen in the future.

SpreadsheetCell::SpreadsheetCell()

{

}

SpreadsheetCell::~SpreadsheetCell()

{

}

The Individual Subclasses

Writing the StringSpreadsheetCell and DoubleSpreadsheetCell classes is just a matter of implementing the functionality that is defined in the parent. Because we want clients to be able to instantiate and work with string cells and double cells, they can’t be abstract — they must implement all of the pure virtual methods inherited from their parent.

String Spreadsheet Cell Class Definition

The first step in writing the class definition of StringSpreadsheetCell is to subclass

SpreadsheetCell.

243

Chapter 10

class StringSpreadsheetCell : public SpreadsheetCell

{

StringSpreadsheetCell declares its own constructor, giving it a chance to initialize its own data.

public:

StringSpreadsheetCell();

Next, the inherited pure virtual methods are overridden, this time without being set to zero.

virtual void set(const std::string& inString);

virtual std::string getString() const;

Finally, the string cell adds a protected data member, mValue, which stores the actual cell data.

protected:

std::string mValue;

};

String Spreadsheet Cell Implementation

The .cpp file for StringSpreadsheetCell is a bit more interesting than the base class. In the constructor, the value string is initialized to a string that indicates that no value has been set.

StringSpreadsheetCell::StringSpreadsheetCell() : mValue(“#NOVALUE”)

{

}

The set method is straightforward since the internal representation is already a string. Similarly, the getString() method simply returns the stored value.

void StringSpreadsheetCell::set(const string& inString)

{

mValue = inString;

}

string StringSpreadsheetCell::getString() const

{

return mValue;

}

Double Spreadsheet Cell Class Definition and Implementation

The double version follows a similar pattern, but with different logic. In addition to the set() method that takes a string, it also provides a new set() method that allows a client to set the value with a double. Two new protected methods are used to convert between a string and a double. Like StringSpreadsheetCell, it has a data member called mValue, this time a double. Because

DoubleSpreadsheetCell and StringSpreadsheetCell are siblings, no hiding or naming conflicts occur as a result.

244