Session Objectives
Describe Single Inheritance Describe Base class and Derived class Access Base class members and use pointers in classes Describe types of inheritance Describe Constructors and Destructors under inheritance Describe how to call Member Functions of the Base Class and Derived Class Describe Container Classes
Linux, C, C++ / Object Oriented Programming with C++ / Session 11 / 2 of 36
Director
Manager
Secretary
Clerk
The derived classes inherit the methods and variables of the base class. They can also have properties and methods of their own.
Class: Manager m_name, m_age, m_Emp_id, m_salary m_department perks, no_of_employees reporting
Advantages
Most important advantage: reusability of code. Result of reusability of code is the development of class libraries.
A class library consists of data and methods encapsulated in a class. Deriving a class from an existing one allows redefining a member function of the base class and also adding new members to the derived class. The base class remains unchanged in the process.
Declaration of a singly derived class is similar to that of any ordinary class, except that the name of the base class also needs to be specified.
class Manager : public Employee
Accessibility (1)
Knowing when a member function or data member of a base class can be used by objects of the derived class.
Class members can always be accessed by member functions within their own class, whether the members are private or public. Objects defined outside the class can access class members only if the members are public.
Accessibility (2)
With inheritance:
Derived class members can access members of the base class if its members are public. Derived class members cannot access the private members of the base class.
Protected members can be accessed only by members of that class. Protected members cannot be accessed by objects or functions from outside the class, such as main(). Protected members is accessible in the derived class.
//base class object //error:not accessible //error:not accessible //valid //derived class object //error:not accessible //error:not accessible //valid
Destructors
Destructors will be called for the derived class first, then for the base class. A destructor for the derived class is to be defined only if its constructor allocates any memory through dynamic memory management.
In contrast, a class X that has a member of another class Y is said to have a Y or X contains Y. This relationship is called a membership or a "has a" relationship.
class X{ public: Y abc; }; //X contains Y
Example of a jet plane: Consider deriving a class for a jet plane from a class called engine. A jet plane is not an engine but has an engine.