Object Oriented Programming Using C++: Inheritance
Object Oriented Programming Using C++: Inheritance
using C++
INHERITANCE
LECTURE-19
1 Qasim M. Rajpoot
NUST School of Electrical Engineering and
Computer Science
WHAT TO STUDY
Inheritance Examples
Inheritance Syntax
Protected access specifier
Redefining member functions
2
INHERITANCE
3
INHERITANCE
Specialization
Augmentation
of existing types
4
INHERITANCE EXAMPLES
Student GraduateStudent
UndergraduateStudent
Shape Circle
Triangle
Rectangle
Employee FacultyMember
StaffMember
Account CheckingAccount
SavingsAccount
5
THE STUDENT CLASS HIERARCHY
student
student_id, print()
year, name
inherits (isa)
graduate_student
dept, print()
thesis
6
INHERITANCE
A natural way to reuse code
Programming by extension rather than reinvention
Object-oriented paradigm is well-suited for this
style of programming
Terminology
Base class (superclass)
Derived class (subclass) Bicycle
is-a relationships
8
INHERITANCE SYNTAX
The derived class inherits from the base class: all public members,
all protected members (will see later)
The additional member functions defined can have the same name
10
as those of the base class (when some base members are
to be redefined)
INHERITANCE SYNTAX
13
EXAMPLE OF INHERITED CLASSES
15
REDEFINING MEMBERS
Some member functions of the base class may not be
suitable for the derived class. These members should
be redefined in the derived class.
16
REDEFINING MEMBERS
class Teacher{ // Base class
private:
string name;
int age, numOfStudents;
public:
void setName (const string & new_name){
name = new_name;
}
void print() const;
};
private no no no
`
21
WHAT IS NEXT?
Inheritance continued…
22