|
|
|
|
|
|
|
Please feel free to extend the minimal code provided in this chapter to enable the animals to act more realistically (when you have more time). |
|
|
|
|
|
|
|
|
When you declare a class, you indicate what class it derives from by writing a colon after the class name, the type of derivation (public or otherwise), and the class from which it derives. The following is an example: |
|
|
|
|
|
|
|
|
class Dog : public Mammal |
|
|
|
|
|
|
|
|
The type of derivation is discussed later in this chapter. For now, always use public. The class from which you derive must be declared earlier, or you will get a compiler error. Listing 16.1 illustrates how to declare a Dog class that is derived from a Mammal class. |
|
|
|
|
|
|
|
|
LISTING 16.1 SIMPLE INHERITANCE |
|
|
|
 |
|
|
|
|
1: //Listing 16.1 Simple inheritance
2:
3: #include <iostream.h>
4: enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };
5:
6: class Mammal
7: {
8: public:
9: // constructors
10: Mammal();
11: ~Mammal();
12:
13: // accessors
14: int GetAge() const;
15: void SetAge(int);
16: int GetWeight() const;
17: void SetWeight();
18:
19: // Other methods
20: void Speak() const ;
21: void Sleep()const;
22:
23:
24: protected:
25: int itsAge;
26: int itsWeight;
27: };
28:
29: class Dog : public Mammal
30: {
31: public: |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|