Expert C Programming

(Jeff_L) #1

How C++ Does Inheritance


Inheritance takes place between two classes (and not between individual functions).


An example of a base class is:


class Fruit { public: peel(); slice(); juice();


private: int weight, calories_per_oz;


} ;


An example of class inheritance is:


class Apple: public Fruit {


public:


void make_candy_apple(float weight);


void bob_for(int tub_id, int


number_of_attempts);


}


An example object declaration is:


Apple teachers;


The example says that class Apple is a specialization of the base class Fruit. The public
keyword on the first line of the inherited Apple class controls accessibility into the base class from
outside the derived class. It is one of several possibilities too detailed to cover fully here.


The syntax for inheritance is uncomfortable at first. The derived class name is followed by a colon
followed by the base class name. It's terse, it doesn't provide much of a hint which is the base class
and which the derived, and it doesn't convey any suggestion of specialization. It's not based on an
existing C idiom, so orthogonality can't guide us.


Don't confuse nesting one class inside another with inheritance. Nesting just brings one class into
another with no special privileges or relationship. Nesting is often used to bring in a container class (a
class that implements some data structure, like a linked list, hash table, queue, etc.). Now that
templates have been added to C++, these are being used for container classes, too.


Inheritance says the derived class is a variation of the base class and there are many detailed
semantics governing how they can access each other. It's the difference between a smaller object being
one part of many in a larger object (nesting), and one object being a specialization of a more general
parent object (inheritance). We wouldn't say that a mammal is nested in a dog; we may say that dogs
inherit mammalian characteristics. Figure out which situation you have, and use the appropriate idiom.

Free download pdf