Deriving C++ Classes
- Deriving Classes
- Creating hierarchies of classes
- Using Virtual Functions
In the previous chapter, you learned how to define independent classes. In this chapter, you'll learn how to define classes derived from other classes.
Deriving classes allows you to reuse the code and data structures belonging to existing classes, as well as to customize and extend existing classes for specific purposes.
You'll also learn how to define and use virtual member functions. Such functions allow you to modify the behavior of existing classes and two write simple, elegant routines that can manage a variety of different program objects.
- Deriving Classes
Suppose you've already written and tested the C Rectangle class described in the previous chapter and are using this class in your program. You now decide that in addition to displaying open rectangles, you'd like to display solid blocks (that is, rectangles filled with solid colors). To do this, you could define define a new class. C Rectangle, Plus some additional facilities required for filling the rectangles once they've been drawn.
If you made CBlock an entirely new class, you'd duplicate much of what you already wrote for the CRectangle class. Fortunately, C++ lets you avoid duplicating code and data by deriving a new class from an existing class. When you derive a new class, it inherits all the data members and member functions belonging to the existing class.
For Example, you could define the class CB lock as follows;
Class CBlock : public CRectangle
{
};
The expression: public CRectangle causes the CBlock class to be derived from the CRectangle class. Because CBlock is derived from CRectangle, in inherits all the data members and member functions belonging to CRectangle. In other words, though the CBlock class definition is empty, the CBlock class automatically possesses the Get Coord, SetCoord, and Draw member functionks, as well as the Left, Top, Right and Bottom data members that were defined for CRectangle. CRectangle is known as the base class, and CBlock as the derived class.
Once you've created a derived class, the next step is to add any new members that are required to meet the specific needs of the new class. For Example, you might expand that CBlock definition as follows:
No comments:
Post a Comment