The Syntax of Derivation ..............................................................................
When you declare a class, you can 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 format of this is:
class derivedClass: accessType baseClass
As an example, if you create a new class called Dogthat inherits from the existing class
Mammal:
class Dog : public Mammal
The type of derivation (accessType) is discussed later in today’s lesson. For now, always
use public. The class from which you derive must have been declared earlier, or you
receive a compiler error. Listing 12.1 illustrates how to declare a Dogclass that is derived
from a Mammalclass.
LISTING12.1 Simple Inheritance
1: //Listing 12.1 Simple inheritance
2: #include <iostream>
3: using namespace std;
4:
5: enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };
6:
7: class Mammal
8: {
9: public:
10: // constructors
11: Mammal();
12: ~Mammal();
13:
14: //accessors
15: int GetAge() const;
16: void SetAge(int);
17: int GetWeight() const;
18: void SetWeight();
19:
20: //Other methods
21: void Speak() const;
22: void Sleep() const;
23:
24:
25: protected:
26: int itsAge;
27: int itsWeight;
28: };
374 Day 12