Inheritance

Chapter 11: Inheritance

Chapter Goals

Derived Classes

Syntax 11.1: Derived Class Definition

class Derived_class_name : public Base_class_name
{
features
};
Example:
class Manager : public Employee {
public:
Manager(string name, double salary, string dept);
string get_department() const;
private:
string department;
};
Purpose: Define a class that inherits features from a base class.

Derived Classes (clocks1.cpp)


Calling the Base-Class Constructor

Syntax 11.2 : Constructor with Base-Class Initializer

Derived_class_name :: Derived_class_name(expressions)
: Base_class_name(expressions)
{
statements
}
Example:
Manager::Manager(string name, double salary, string dept)
: Employee(name, salary)
{
department = dept;
}
Purpose: Supply the implementation of a constructor, initializing the base class before the body of the derived-class constructor.

Calling Base-Class Member Functions

Calling Base-Class Member Functions (clocks2.cpp)



Polymorphism

Syntax 11.3: Virtual Function Definition

class Class_name
{
virtual return_type function_name(parameter1, parameter2, ..., parametern);
. . .
};
Example:
class Employee
{
public:
virtual double get_salary();
. . .
};
Purpose: Define a dynamically bound function that can be redefined in derived classes. When the function is called, the actual type of the implicit parameter determines which version of the function executes.

Polymorphism (clocks3.cpp)