Instructors' Guide


Introduction Terminology Expressions Control Objects Inheritance Technology Summary

Inheritance

Not only is C++ an efficient language, but it also offers features lacking in Smalltalk and Eiffel. In particular, it allows us to make a distinction between (private) members of a class that are inaccessible to everybody (including descendants), (protected) members that are inaccessible to ordinary clients (but not to descendants), and (public) members that are accessible to everybody.

Inheritance

  class A { 
ancestor
public: A() { n = 0; } void add( int i ) { n = n + i; } virtual int val() { return n; } protected:
private would deny access to D
int n; }; class D : public A {
descendant
public: D() : A() { } int val() { return n % 2; } };

slide: C++ -- inheritance

In the example in slide cc-inheritance, using private instead of protected would deny access to the instance variable n of A. The example also illustrates the use of virtual functions (to refine the observation val to deliver the value of the object modulo two) and the invocation of constructors of ancestor classes (which need not be explicitly specified by the user).

Allowing descendants full access to the instance variables defined by ancestors, however, increases the dependency on the actual implementation of these ancestors, with the risk of a total collapse when the implementation of an ancestor changes.