0% found this document useful (0 votes)
10 views

Week6 DerivedClasses

The document discusses derived classes in C++. It introduces base and derived classes, different types of inheritance, and provides examples of how derived classes inherit and extend base classes. It also covers accessing members of base and derived classes and the difference between inheritance and composition.

Uploaded by

mujahid
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Week6 DerivedClasses

The document discusses derived classes in C++. It introduces base and derived classes, different types of inheritance, and provides examples of how derived classes inherit and extend base classes. It also covers accessing members of base and derived classes and the difference between inheritance and composition.

Uploaded by

mujahid
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 43

Derived Classes in C++

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)

CS-2303, C-Term 2010 Derived Classes in C++ 1


Outline

• 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

• Deitel & Deitel, Chapter 23

• Note:– Like most of the rest of the book,


this chapter is written mostly for someone
who has never heard of classes, subclasses,
and object-oriented programming
• Especially someone who has never seen Java

CS-2303, C-Term 2010 Derived Classes in C++ 3


History

• The whole notion of classes, subclasses,


and inheritance came from Simula 67
• A generalization of notion of records (now known
as structs) from Algol- and Pascal-like languages
in 1960s and early 70s

– A (very nice) programming language developed


in Norway for implementing large simulation
applications

CS-2303, C-Term 2010 Derived Classes in C++ 4


Terminology

• 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
CS-2303, C-Term 2010 Derived Classes in C++ 5
Terminology (continued)

• C++ • Java
– Derived Class – Subclass

– Base Class – Superclass

CS-2303, C-Term 2010 Derived Classes in C++ 6


Introduction (continued)
• 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.
CS-2303, C-Term 2010 Derived Classes in C++ 7
Deitel & Deitel, Fig. 23.2
er sity
univ
of a
Class Hierarchy em
r s
be ty
M muni
com

CS-2303, C-Term 2010 Derived Classes in C++ 8


Three Types of Inheritance in C++

• 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
CS-2303, C-Term 2010 Derived Classes in C++ 9
Example — public class
class Employee { es
e
string givenName, familyName; ploy e
Em ar
date hiringDate; re yee s
a
rs plo
short department; ag e m
an ll E
... l M t a
Al t no rs
}; bu nage
Ma
class Manager: public Employee {
set <Employee *> group;
short level;
...
}
CS-2303, C-Term 2010 Derived Classes in C++ 10
Example — public class
class Employee {
string givenName, familyName;
date hiringDate;
short department;
...
};

class Manager: public EmployeeNote:


{ this is an example of
set <Employee *> group; the use of a container
short level; class

...
}
CS-2303, C-Term 2010 Derived Classes in C++ 11
Important Note

• 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
CS-2303, C-Term 2010 Derived Classes in C++ 12
protected – New Access Specifier

class Employee {
protected:
string givenName, familyName;
date hiringDate;
short department;
...
};

class Manager: public Employee {


set <Employee *> group;
short level;
...
}
CS-2303, C-Term 2010 Derived Classes in C++ 13
protected (continued)

• 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
CS-2303, C-Term 2010 Derived Classes in C++ 14
Difference between
Inheritance and Composition
• 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
CS-2303, C-Term 2010 Derived Classes in C++ 15
Base Classes and Derived Classes

• 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 vehicles

CS-2303, C-Term 2010 Derived Classes in C++ 16


Base Classes and Derived Classes (continued)

• I.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

CS-2303, C-Term 2010 Derived Classes in C++ 17


Questions?

CS-2303, C-Term 2010 Derived Classes in C++ 18


Deitel & Deitel §23.4 — Five Examples

1. Create a CommissionEmployee class with


private data members:–

First name, last name, SSN, commission rate,
gross sale amount.
2. Create a BasePlusCommissionEmployee
class without inheritance but with private
data members:–
• First name, last name, SSN, commission rate,
gross sale amount, and base salary.
• Copying code is not code re-use!
CS-2303, C-Term 2010 Derived Classes in C++ 19
Digression – Code Re-use
• Fundamental principle of software engineering
• A body of code is a living, evolving thing
– In response to bug fixes, changes in requirements, additional
features, new environments, etc.
• As a practical matter, copies of bodies of code cannot keep
up with each other
– Divergent bug fixes, different evolving requirements, different
development teams, etc.
• If you really want your hard work to support multiple
purposes, applications, requirements, etc.
– You really need a way for those purposes to inherit your code
rather than copy it.
CS-2303, C-Term 2010 Derived Classes in C++ 20
Deitel & Deitel §23.4 — Five Examples

1. Create a CommissionEmployee class with


private data members:–

First name, last name, SSN, commission rate,
gross sale amount.
2. Create a BasePlusCommissionEmployee
Likewise, it is easier to copy and modify
class without the
inheritance
HashTablebut with
class private
of PA5 than it is to
data members:–build a derived class!
• First name,However,
last name,PA5 requires
SSN, a derivedrate,
commission class!
As a one-off project, it is easier to copy
gross sale amount, and base salary.
and modify CommissionEmployee than to
build a•derived
Copying
class!code is not code re-use!
CS-2303, C-Term 2010 Derived Classes in C++ 21
Deitel & Deitel §23.4 — Five Examples (cont.)

3. Create a CommissionEmployee base class


and BasePlusCommissionEmployee
inheritance hierarchy with private members.
4. Create a CommissionEmployee base class
and BasePlusCommissionEmployee
inheritance hierarchy with protected
members.
5. Create a CommissionEmployee base class
and BasePlusCommissionEmployee
inheritance hierarchy with private members
but access through public member functions.
If youCS-2303,
need to2010
C-Term see a detailed
Derived Classes in C++ 22

example, refer to one of these.


Constructors and Destructors
• Constructor:–
– Derived class constructor is called to create derived
class object
– Invokes base class constructor before derived class
initializer list & constructor body
– … and so on up class hierarchy
• Destructor:–
– Derived class destructor body is executed first
– Then destructors of derived class members
– And then destructor of base class
– … and so on up class hierarchy
CS-2303, C-Term 2010 Derived Classes in C++ 23
Instantiating Derived-class Object

• Derived-class constructor invokes base class


constructor either
– implicitly (via a base-class member initializer) or
– explicitly (by calling the base classes default
constructor).
• Base of inheritance hierarchy
– The last constructor called in an inheritance chain is at
the base of the hierarchy
– This constructor is the first constructor body to finish
executing

CS-2303, C-Term 2010 Derived Classes in C++ 24


Software Engineering Observation 23.7

• When a program creates a derived-class object,


– the derived-class constructor immediately calls the
base-class constructor,
– the base-class constructor’s body executes,
– then the derived class’s member initializers execute,
and
– finally the derived-class constructor’s body executes
• This process cascades up the hierarchy if the
hierarchy contains more than two levels.

CS-2303, C-Term 2010 Derived Classes in C++ 25


Constructors and Destructors
in Derived Classes
• Destroying derived-class objects
– Chain of destructor calls
• Reverse order of constructor chain
• Destructor of derived-class called first.
• Destructor of next base class up hierarchy is called next.
• This continues up hierarchy until the final base class is
reached.
– After final base-class destructor, the object is removed from
memory.
• Base-class constructors, destructors, and
overloaded assignment operators are not inherited
by derived classes.
CS-2303, C-Term 2010 Derived Classes in C++ 26
Software Engineering Observation 23.8

• Suppose that we create an object of a derived class


where both the base class and the derived class
contain objects of other classes.
• When an object of that derived class is created,
first the constructors for the base class’s member
objects execute, then the base-class constructor
executes, then the constructors for the derived
class’s member objects execute, then the derived
class’s constructor executes.

CS-2303, C-Term 2010 Derived Classes in C++ 27


Software Engineering Observation 23.8

• Destructors for derived-class objects are


called in the reverse of the order in which
their corresponding constructors are called.

CS-2303, C-Term 2010 Derived Classes in C++ 28


Questions?

CS-2303, C-Term 2010 Derived Classes in C++ 29


Redefinition of Base Class Members

• Suppose that base class has a member


• E.g. void print()
• Knows only how to print information from base
class

• Define same member in derived class


• E.g. void print()
• Knows how to print info for derived class
• Needs to call base class print() function to print
base class info
CS-2303, C-Term 2010 Derived Classes in C++ 30
Redefinition of Base Class Members (continued)

• Derived class
void print() {
// print derived class info

BaseClass::print(); //prints base info

// more derived class stuff


}
General principle: when in derived class
• See Deitel &scope,
Deitel, Figneed
if you 23.25
to access anything
• Lines 50-59
in base class and there is a naming
conflict, use '::' scope resolution operator
CS-2303, C-Term 2010 Derived Classes in C++ 31
Accessing Members of
Base and Derived Classes
• Let B be a base class with public members m and n
• Let D be a derived class with public members m
and p
• I.e., D redefines member m
• E.g., print() function of previous example
• Consider the following:–
B objB;
D objD;
B *ptrB;
D *ptrD;

CS-2303, C-Term 2010 Derived Classes in C++ 32


Accessing Members (continued)

objB.m and objB.n are both legal


– access members of base class
objD.m and objD.p are both legal
– access members of derived class
objD.n is also legal
– accesses member of base class!
objB.p is not legal
– Class B has no member named p!
CS-2303, C-Term 2010 Derived Classes in C++ 33
Accessing Members (continued)

ptrB = new B();


ptrB -> m and ptrB -> n are both legal
– access members of base class

ptrD = new D();


ptrD -> m and ptrD -> p are both legal
– access members of derived class

CS-2303, C-Term 2010 Derived Classes in C++ 34


Accessing Members (continued)

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?

CS-2303, C-Term 2010 Derived Classes in C++ 37


Loose End:–
Three Types of Inheritance in C++
• 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
CS-2303, C-Term 2010 Derived Classes in C++ 38
Let D be derived from B

• If B is a private base class:–


• I.e., class D: private B {}
• Public and protected members of B can only be used
by member and friend functions of D.
• Only members and friends of D can convert D* into B*

• I.e., outside of member and friend functions of D


• Dptr -> p is not allowed (where p is a member of B)
• Bptr = Dptr is not allowed

CS-2303, C-Term 2010 Derived Classes in C++ 39


Let D be derived from B (continued)

• 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*

• I.e., outside of member and friend functions of D or its


derived classes
• Dptr -> p is not allowed (where p is a member of B)
• Bptr = Dptr is not allowed
CS-2303, C-Term 2010 Derived Classes in C++ 40
Let D be derived from B (continued)

• 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

• This topic covered the basics of inheritance


in C++

• There is much, much more to say about


inheritance after we cover polymorphism

CS-2303, C-Term 2010 Derived Classes in C++ 42


Questions?

CS-2303, C-Term 2010 Derived Classes in C++ 43

You might also like