Simple inheritance in C++


1: //Listing 12.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();
21: void Sleep();
22:
23:
24: protected:
25: int itsAge;
26: int itsWeight;
27: };
28:
29: class Dog : public Mammal
30: {
31: public:
32:
33: // Constructors
34: Dog();
35: ~Dog();
36:
37: // Accessors
38: BREED GetBreed() const;
39: void SetBreed(BREED);
40:
41: // Other methods
42: // WagTail();
43: // BegForFood();
44:
45: protected:
46: BREED itsBreed;
47: };

This program has no output because it is only a set of class declarations without their implementations. Nonetheless, there is much to see here.

Analysis: On lines 6-27, the Mammal class is declared. Note that in this example, Mammal does not derive from any other class. In the real world, mammals do derive--that is, mammals are kinds of animals. In a C++ program, you can represent only a fraction of the information you have about any given object. Reality is far too complex to capture all of it, so every C++ hierarchy is an arbitrary representation of the data available. The trick of good design is to represent the areas that you care about in a way that maps back to reality in a reasonably faithful manner.

The hierarchy has to begin somewhere; this program begins with Mammal. Because of this decision, some member variables that might properly belong in a higher base class are now represented here. For example, certainly all animals have an age and weight, so if Mammal is derived from Animal, we might expect to inherit those attributes. As it is, the attributes appear in the Mammal class.

To keep the program reasonably simple and manageable, only six methods have been put in the Mammal class--four accessor methods, Speak(), and Sleep().

The Dog class inherits from Mammal, as indicated on line 29. Every Dog object will have three member variables: itsAge, itsWeight, and itsBreed. Note that the class declaration for Dog does not include the member variables itsAge and itsWeight. Dog objects inherit these variables from the Mammal class, along with all of Mammal's methods except the copy operator and the constructors and destructor.
Share this article :
 
Copyright © 2012. Best Online Tutorials | Source codes | Programming Languages - All Rights Reserved