10.6 Inheritance


10.6 Inheritance

The sample Frog class created thus far exposed the following abilities: Eat, Sleep, and Jump. In the real world, over thousands of years, a new kind of frog may evolve from this original population of frogs and develop new abilities, effectively giving two species of frog. For example, the new species would inherit all of the abilities of its ancestor, and additionally it could develop its own ability, specifically the ability to fly. The two kinds of frog would therefore be Frog (the original) and FlyingFrog (the new). FlyingFrog is said to have descended, or derived, from Frog, and Frog is an ancestor of FlyingFrog.

image from book
Figure 10.1

Using the techniques we've learned thus far to implement this ancestor-derived relationship between classes in C++, programmers would need to create two classes: one for Frog and one for FlyingFrog. FlyingFrog, though, will need to tediously duplicate all the Frog code since it's supposed to inherit all the properties and methods of class Frog. To alleviate this duplication problem, C++ offers inheritance of classes, allowing one class to inherit all the properties and methods of another.

10.6.1 Class Inheritance

Class inheritance allows one class to inherit all properties and methods from another. The properties and methods of the ancestor class also become properties and methods of the descendant class. In class terminology, the descendant class is called the subclass or derived class, and the ancestor class is called the superclass. Consider the following code:

      class Frog      {         int Color;         int Height;         int Width;      public:         void Jump();         void Sleep();         void Eat();         int operator+(Frog param);    //Defines Add Operator         int operator-(Frog param);    //Defines Add Operator      };      class FlyingFrog : public Frog      {         public:             void Fly();      } 

10.6.2 Multiple Inheritance

While one class can inherit from another, it can also inherit from many; inheritance is not restricted to a one-to-one relationship. Inheriting from more than one class is called multiple inheritance, and such classes inherit all properties and methods from all superclasses. Consider the following code:

      class SuperFrog : public Frog, public GeneralClass      {         public:            void Fly();      }; 




Introduction to Game Programming with C++
Introduction to Game Programming with C++ (Wordware Game Developers Library)
ISBN: 1598220322
EAN: 2147483647
Year: 2007
Pages: 225
Authors: Alan Thorn

Similar book on Amazon
Beginning C++ Through Game Programming
Beginning C++ Through Game Programming
Beginning Game Programming
Beginning Game Programming
The Ultimate Guide to Video Game Writing and Design
The Ultimate Guide to Video Game Writing and Design

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