Inheritance
is a form of software reuse where a
new class is created to
– absorb
an existing class’s data and behaviors, and
– enhance
them with new capabilities
The new
class, the derived class, inherits
the members of the existing class, known as the base class
A direct
base class is the base class from which a derived class explicitly inherits. An
indirect base class is inherited from two or more levels up in the class
hierarchy.
In single
inheritance, a class is derived from one base class. With multiple inheritance,
a derived class inherits from multiple base classes. public:: every object of a
derived class is also an object of its base class
• Note,
base-class objects are NOT objects of their derived classes. private:: is
essentially an alternative to composition
• I.e.,
derived class members not accessible from outside
protected::
is rarely used
class Employee {
string givenName, familyName;
date hiringDate;
short department;
...
};
class Manager: public Employee {
set <Employee *> group;
short level;
...
}
Member
functions of derived class cannot
directly access private members of base class
•
Example:–
Manager member
functions in previous example cannot read manager’s own name! Because data members of a class are by
default private
A base class’s protected
members can be accessed by members and friends of the base class, and
members and friends of any class derived from the base class.
Derived-class member functions can refer to public and protected members of the base class. By simply using their names
is-a relationship:: inheritance
– e.g.,
derived class object, car, is an object of the base class vehicle
– e.g.,
derived class object, Manager, is an object of the base class Employee
– has-a relationship:: composition
– e.g., a
TreeNode object has (i.e., contains) a member object of type string Base classes typically represent larger sets of objects than
derived classes Example
– Base
class: vehicle
•
Includes cars, trucks, boats, bicycles, etc.
– Derived
class: car
a
smaller, more-specific subset of vehiclesI.e., base classes have more objects
• But fewer
data and function members
• Derived
classes have only subsets of the
objects
• Hence the
term subclass
• But a
derived class has more data and function members
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.