Week6 DerivedClasses
Week6 DerivedClasses
CS-2303
System Programming Concepts
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie, from
C: How to Program, 5th and 6th editions, by Deitel and Deitel, and from
The C++ Programming Language, 3rd edition, by Bjarne Stroustrup)
• Introduction
• Base Classes and Derived Classes
• Some Examples of Base Class and Derived
Class Relationships
• Constructors and Destructors in Derived
Classes
• Accessing Members of Base and Derived
Classes
CS-2303, C-Term 2010 Derived Classes in C++ 2
Reading Assignment
• C++ • Java
– Derived Class – Subclass
...
}
CS-2303, C-Term 2010 Derived Classes in C++ 11
Important Note
• Example:–
– Manager member functions in previous
example cannot read manager’s own name!
– Because data members of a class are by default
private
CS-2303, C-Term 2010 Derived Classes in C++ 12
protected – New Access Specifier
class Employee {
protected:
string givenName, familyName;
date hiringDate;
short department;
...
};
• Derived class
void print() {
// print derived class info
ptrB = ptrD;
– ptrB now points to a member of the derived
class
– which by definition is a member of the base
class!
ptrB -> m and ptrB -> n are both legal
– access members of base class object
– Even though object is a member of derived
class, with its own redefined member m!
CS-2303, C-Term 2010 Derived Classes in C++ 35
Accessing Members (continued)
ptrB = ptrD;
ptrB -> p is not legal
– Because ptrB only knows about B’s members!
• Rule:–
– So far, which member to access depends
entirely on the type of the accessing pointer (or
accessing object)
– To bend that rule, need polymorphism and
virtual members.
CS-2303, C-Term 2010 Derived Classes in C++ 36
Questions?
• If B is a protected base:–
• I.e., class D: protected B {}
• Public and protected members of B can only be used by member
and friend functions of D and also by member and friend
functions of classes derived from D
• Only members and friends of D and its derived classes can
convert D* into B*
• If B is a public base:–
• I.e., class D: public B {}
• Public members of B can be used by any function
• Protected members of B can be used by member and
friend functions of D and also by member and friend
functions of classes derived from D
• Any function can convert D* into B*
• I.e.,
• Dptr -> p is allowed (where p is a member of B)
• Bptr = Dptr is allowed
CS-2303, C-Term 2010 Derived Classes in C++ 41
Summary – Inheritance