Tuesday, October 10
Inheritance - Introduction

Topics

Introduction
- Key concept that distinguishes object-oriented programming from procedural programming
- A natural and intuitive technique for organizing large scale program libraries
- Provides facility for sharing similarities yet maintaining uniqueness
- Allows us to extend and reuse existing code without having to rewrite code
 

Terminology
- Classes from which to share data and methods: base (preferred), superclass (discouraged but used), parent (discouraged but used)  
- Classes that inherit data and methods from other classes: derived (preferred), subclass (discouraged), child (discouraged)
 

Technique
- Any existing class can be a base class.
- The syntax p
rovides a very simple indication that a new class derives from a base class.

- The derived class incorporates all the features (data + methods) of base class.
- All the code in the base class works exactly the same in the derived class.
- Only the additional code needs to be written for the new features in the derived class.  The existing code does not need to be re-written.

- The derived class inherits the existing features of the base class and can add features of its own.
- The derived class can access all public functions of the base class, as if they had been re-written in the derived class. 
- It cannot access the private data of the base class, but it still has all that data within itself without being re-declared.  The base class data can be manipulated with the base class's public functions.
 
- No new code required to implement new derived class except for those operations that...
        1) extend (or add to) the members inherited from the base class
        2) replace the members inherited from the base class 

 

Advantages

Programming
- Putting common code in the base class encodes similarities among related derived classes classes without repetition of code
- Establishes foundation for future derived classes

Design
- Attempts to represent in software a model of the real world
- Reflect existence and organization of the natural abstractions in a  problem solution
- Good object oriented design creates inheritance relations that reflect the relations of objects in the real world
 

Software engineering
- Long lifetime, undergoes many changes and extensions during existence
- Extensibility: degree to which software can be modified to add new features  
 
 

Class derivation syntax

class DerivedName : public BaseName
{
public:

private:

};

DerivedName - Derived class's new name

BaseName - Base class's existing name

:  -   indicates derivation from a previously defined class

public - keyword indicating visibility of base class members in derived classes

class DerivedName : public BaseName
"Publicly derived class"
    - Treat all public members of the base as being public in derived class
    - Private base class members remain private
    - Most commonly used form of derivation

class DerivedName : private BaseName
"Privately derived class"
    - All base class members are treated as being private in derived class
    - True even if some of the members are public in the base class
    - Not as common - it means that programmers using this class can only use the additional public functions that you add to the derived class.  They can not use any functions from the base class, public or private.


 

Example

// Describes a general vehicle
class Vehicle
{
public:

    // Constructor
    Vehicle() { distance = 0.0; speed = 0.0; }

    // duration = distance/speed
    float computeDuration();

    // Access methods
    float getSpeed() { return speed; }
    void setSpeed(float s) { speed = s; }
    float getDistance() { return distance; }
    void setDistance(float d) { distance = d; }
 

private:
    float distance;    // in miles
    float speed;       // in miles per hour

};

float Vehicle::computeDuration()
{
    return ( distance / speed );
}

- We have a vehicle class describing general attributes (an abstraction)
- General attributes include both data (internal information) and behavior (methods)
- We'd like to design specific types of vehicles (i.e. cars, planes)
- Many attributes of the specific have already been described in the general class
- This is an ideal case to use inheritance (use general class to create more specific class)
 
 

// Describes a wheeled vehicle; derived from vehicle class
class WheelVehicle : public Vehicle
{
public:

    // Constructor
    WheelVehicle() { wheels = 0; }

    // Access methods
    void setWheels(int w) { wheels = w; }
    int getWheels() { return wheels; }
 

private:
    int wheels;        // number of wheels

};


- WheelVehicle is a derived class from the base class Vehicle
- Extend base class by adding attributes describing more specific components
- WheelVehicle objects can use Vehicle class public methods
- Can derived class directly access the speed and distance members?
 
 

// Describes a winged vehicle; derived from vehicle class
//    Note private derivation
class WingVehicle : public Vehicle
{
public:

    // Constructor
    WingVehicle() { wings = 0; }

    // Access methods
    void setWings(int w) { wings = w; }
    int getWings() { return wings; }
 

private:
    int wings;        // number of wings

};


- WingVehicle is a derived class from the base class Vehicle similar to the  WheelVehicle class
 
 

#include <stdio.h>

main()
{
    WheelVehicle wheelv;
    wheelv.setWheels(4);
    wheelv.setSpeed(65.0);
    wheelv.setDistance(300.0);
    printf( "Duration for wheelv: %f hrs\n", wheelv.computeDuration() );

    WingVehicle biplane;
    biplane.setWings(4);
    biplane.setSpeed(300.0);
    biplane.setDistance(300.0);
    printf( "Duration for plane: %f hrs\n", biplane.computeDuration() );
}
Output
Duration for wheelv: 4.615385 hrs
Duration for plane: 1.000000 hrs


- We can call methods of base class in derived classes
- We can reuse methods of base class in derived classes
- Which base class methods are reused?
- Which methods called by derived objects are not reused?
 
 
 

Class Hierarchy
- Derived classes can be base classes for further related derivations
- Deriving classes from other derived classes sets up a chain of classes
- Also called a class hierarchy (organized grouping of related classes)
- Classes can have multiple base classes, but this is generally considered a poor feature of C++ and should only be used with great care.  This feature is called "Multiple Inheritance".
- A derived class inherits members from all classes proceeding up the chain(s)
- We'll concentrate on the basic parent -> child -> grandchild relationship
- Suppose we need to define a specific type of wheeled vehicle
- General and specific attributes already defined in WheelVehicle (and parent Vehicle)
- Reuse these classes and derive new class to extend, replace, or add with further attributes
 

// Describes a specific type of wheeled vehicle
//    Derived from wheelvehicle class (derived from vehicle class)
class Truck : public WheelVehicle
{
public:
    Truck() { carryingLoad = 0.0; }

    void setLoad( float l ) { carryingLoad = l; }
    float getLoad() { return carryingLoad; }
 

private:
    float carryingLoad;

};
 
 

#include <stdio.h>

main()
{
    WheelVehicle wheelv;
    wheelv.setWheels(4);
    wheelv.setSpeed(65.0);
    wheelv.setDistance(300.0);
    printf( "Duration for wheelv: %f hrs\n", wheelv.computeDuration() );
 

    Truck semi;
    semi.setLoad(2);
    semi.setWheels(18);
    semi.setSpeed(55.0);
    semi.setDistance(300.0);
    printf( "Duration for truck: %f hrs\n", semi.computeDuration() );
}
 

Output
Duration for wheelv: 4.615385 hours
Duration for truck: 5.454545 hours


- We can call methods of parent and "grandparent" class
- Which methods (of which class) are reused?
- Which methods are not reused?
 
 

Protected members
- Consider the accessibility chart for base class members, derived members, and users
 

Keyword Available in
b
ase
class
Available in
d
erived classes
Available in
all
classes
private

*

   
protected

*

*

 
public

*

*

*

- Members of derived classes can access protected members of base class
- Allows for good design practice and provide easier access for derived classes

Example

// Describes a general vehicle
class Vehicle
{
public:

    // Constructor
    Vehicle() { distance = 0.0; speed = 0.0; }

    // Access methods
    float getSpeed() { return speed; }
    void setSpeed(float s) { speed = s; }
    float getDistance() { return distance; }
    void setDistance(float d) { distance = d; }

protected:

    // Notice that computeDuration is now only for use
    //     by the derived classes
    float computeDuration();

private:
    float distance;    // in miles
    float speed;       // in miles per hour

};

#include <stdio.h>

main()
{
    WheelVehicle wheelv;
    wheelv.setWheels(4);
    wheelv.setSpeed(65.0);
    wheelv.setDistance(300.0);
    printf( "Duration for wheelv: %f hrs\n", wheelv.computeDuration() );
 

    Truck semi;
    semi.setLoad(2);
    semi.setWheels(18);
    semi.setSpeed(55.0);
    semi.setDistance(300.0);
    printf( "Duration for truck: %f hrs\n", semi.computeDuration() );
}
 

Output
Compiler error because computeDuration is not public anymore, and has been reserved only for internal use by the base and derived classes.

 

- Why do you think members in the derived class are sometimes protected?
 

Readings

Deitel & Deitel Fourth Edition: 9.1 - 9.3

 

Back to Csc 125 - Computer Science II, Programming in C++
  Scott Badman   Office: B132   Phone: 353-2250   sbadman@parkland.edu  

Parkland College, 2400 W. Bradley Avenue, Champaign, IL 61821