Inheritance - PowerPoint PPT Presentation

1 / 39
About This Presentation
Title:

Inheritance

Description:

class Spider : public Car. public: void accelerate() { _speed = 5 } Inheritance ... class Elevator : public Lift, public Equipment ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 40
Provided by: anniegro
Category:

less

Transcript and Presenter's Notes

Title: Inheritance


1
Inheritance
  • CS241
  • Western Washington University

2
Making Classes More Life-like
  • Classes represent concepts
  • Concepts can be extended
  • Concepts can be abridged
  • Concepts can be modified
  • Concepts are extended, abridged, and/or modified
    to produce new concepts, without altering
    existing concepts

3
Inheritance as a Solution
  • The problem is
  • How do we make classes mimic concepts?
  • One solution is Inheritance!
  • Inheritance models the Is-A relationship
  • between objects.
  • Is-A allows the new class to be specified in
  • terms of the old class.
  • Typical signs that 2 classes have an inheritance
  • relationship
  • They are common in general ways (data, behavior)
  • They are different in specific ways (data,
    behavior)
  • One is a specialization of the other

4
Inheritance Syntax
ifndef _EMPLOYEE_H_ define _EMPLOYEE_H_ class
Employee public enum Gender MALE,
FEMALE string _name Gender
_gender class Worker public
Employee public float _wage class
Manager public Employee public unsigned int
_salary unsigned int _level endif //
_EMPLOYEE_H_
5
More Derived Classes
class Secretary public Worker public unsigne
d int _wpm class Engineer public
Worker public string _school string
_degree
6
Inheritance Usage
include Employee.h int main() Secretary
s Engineer e s._name Damon s._gender
EmployeeMALE s._wage 11.50 s._wpm
75 e._name Marie e._gender
EmployeeFEMALE e._wage 25.25 e._school
WWU e._degree CS e._wpm 45
7
Observations
First of all, note that a derived class inherits
the data from all its ancestors. Second, notice
that there is no limit to the number of levels
allowed in an inheritance hierarchy. Other than
that, do you see any errors? Notice anything
odd?
8
An Inheritance Hierarchy
Employee
Manager
Worker
Secretary
Engineer
9
The Jargon
  • The class being extended can be called
  • base class
  • parent class
  • ancestor class
  • superclass
  • The class created by the extension can be called
  • derived class
  • child class
  • subclass
  • You can create several levels of inheritanceas
    the previous diagram showed

10
Member Functions
Member functions are inherited just like
member data.. class Employee public void
who() void Employeewho() cout ltlt
Name ltlt _name ltlt endl int
main() Secretary s Engineer
e s.who() e.who()
11
Overriding Member Functions
Base class member functions can be overridden
in derived classes. class Car public int
_speed void accelerate() _speed 2
class Yugo public Car public void
accelerate() _speed 1 class Spider
public Car public void accelerate() _speed
5
12
Overriding Usage
int main() Yugo y Spider s y.accelerate()
s.accelerate() What if I wanted accelerate
to take an optional parameterhow do I do this?
13
More on Overriding
I also have the option of implementing an
overridden member function in a derived class by
making a call to a member function in the
base class! This is yet another way behavior can
be inherited in the derived class. Write a
show() member function for the Employee class
hierarchy.
14
Derived Names Hide Base Names
Any function in a derived class hides all
functions of the same name in its base
class. This is true even if the derived class
and the base class functions are distinguishable
by their arguments Just as a name defined in a
block hides anything by that name in an outside
block, a class member hides any member by the
same name in the base class. Fortunately, most
compilers will issue warnings when this happens.
15
Derived Names Example
class Rectangle public Rectangle(int wd, int
ht) _width(wd), _height(ht) void
draw() private int _height, _width class
Square public Rectangle public Square(int
side) Rectangle(side, side) void draw(int
thinkness) int main() Square
sq(20) sq.draw() // ERROR sq.draw(2) //
OK return 0
16
Initializing Base Classes
  • The process of creating a derived class includes
    the instantiation of all its base classes
  • Each class is responsible for the initialization
    of its immediate base class
  • In syntax and principle, initializing a base
    class is very similar to initializing a member
    variable
  • use a member initialization list!
  • inheritance and containment are not so different
    syntactically!

17
Base Class Initialization Syntax
class Rectangle public Rectangle(int wid, int
len) private int _width int
_length class Square public Rectangle
public Square() SquareSquare()
SquareSquare() Rectangle(10, 10)
SquareSquare() Rectangle_width
10 Rectangle_length 10
18
Access to Base Class Members
What is the significance of the keyword public
in class Square public Rectangle It
defines the derivation type. With inheritance,
access to base class members is determined by 2
things 1) Access level in the body of the
classpublic, private, protected 2) Derivation
typealso public, private, protected
19
Access (cont.)
The following questions are answered by
access levels in the body of the class 1)
Which parts of a base class can be accessed by a
client of the base class? 2) Which parts of a
base class can be accessed by its derived
class? The following questions are answered by
derivation type 1) Which parts of a base class
can be accessed by clients of its derived
class? 2) Which parts of a base class can be
accessed by derived classes of its derived class?
20
Why So Much Security?
Actually, these 2 categories of security cover
entirely different things. The access levels
cover 1) access to clients 2) access to
immediately derived classes of a class The
derivation type covers 1) access to base class
members by clients 2) access to base class
members by derived classes of the derived class
21
Access Levels
So far, weve seen public and private. Do
either of these access levels address access
to immediately derived classes of a
class? Nope. Thats what protected is
for! protected means exactly that immediately
derived classes can access Now what
specifically do public, private, and protected
mean as the derivation type? Its easiest to see
by some examples.
22
Access Levels Summary
All class members fall into on the of the
following categories(access levels) public
means clients and derived classes can
access protected means derived classes can
access private means only member functions of
the same class and friends of the class can
access
23
Access Propagation
Putting public, protected, or private in the
class derivation statement tells the derived
class the power it has to provide access to base
class functions to its clients and further
derived classes. This use of these keywords is
called access propagation or derivation type
24
Access Propagation Syntax
class Rectangle public Rectangle(int wd, int
ht) _width(wd), _height(ht) int height()
constreturn _height int width() constreturn
_width private int _height, _width class
Square public Rectangle public Square(int
side) Rectangle(side, side) int side()
constreturn height() int main() Square
sq(20) int sq_wid sq.width() int sq_ht
sq.height() int sq_side sq.side() return
0
25
Access Propagation Syntax(cont.)
class Rectangle public Rectangle(int wd, int
ht) _width(wd), _height(ht) int height()
constreturn _height int width() constreturn
_width private int _height, _width class
Square private Rectangle public Square(int
side) Rectangle(side, side) int side()
constreturn height() int main() Square
sq(20) int sq_wid sq.width() // ERROR int
sq_ht sq.height() // ERROR int sq_side
sq.side() return 0
26
Access Propagation Summary
  • In a public derivation
  • public members of the base class are public
    members of the derived class
  • protected members of the base class are protected
    members of the derived class
  • In a protected derivation
  • public members of the base class are protected
    members of the derived class
  • protected members of the base class are protected
    members of the derived class
  • In a private derivation
  • public members of the base class are private
    members of the derived class
  • protected members of the base class are private
    members of the derived class
  • In all cases, the private members of the base
    class are inaccessible to the derived class

27
public vs.private Inheritance
Consider the following class class Array
public void insert(int index, int value)
int get(int index) We could use public
inheritance to implement a stack as
follows class Stack public Array public
Stack() _top(0) void push(int value)
insert(_top, value_ int pop() return
get(--_top) private int _top int
main() Stack st st.push(10)
st.insert(1,15)
28
public vs.private Inheritance (cont.)
Whats wrong with public inheritance? public
visibility of Arrays interface Recall that
private inheritance makes all public and
protected members of the base class private in
the derived class. class Stack private Array
... int main() Stack st
st.push(10) st.insert(1,15) //
ERROR private inheritance implements an
as-a or implemented-with relationship.
29
Selective Exposure of Base Class Members
Using the using keyword, you can selectively
expose members of the base class. class Base
public int pubBase void pubBaseFunc() void
pubBaseFunc(int index) protected int
proBase private int priBase class Derived
private Base public using
BasepubBase using BasepubBaseFunc protected
using BaseproBase Which pubBaseFunc is
exposed?
30
Derived and Base Class Interoperability
An instance of a publicly derived class may be
used anywhere an instance of its base class is
expected. A pointer to a publicly derived class
may be used anywhere a pointer to a base class
instance is allowed. A reference to a publicly
derived class instance can be used where a
reference to a base class instance is allowed.
31
Interoperability Examples
class Rectangle class Square public
Rectangle int main() Rectangle
rect(3,4) Square sq(5) Rectangle rp
rect Rectangle rr rect Square sp
sq Square sr sq rp sq rp
sp Rectange rr2 sq sp rp //
ERROR Square sr2 rect // ERROR return 0
32
Multiple Inheritance
Most real-world objects have several aspects of
behavior. Each aspect embodies a different
concept and the real world entity is a composite
of several concepts. class Swimmer public
Swimmer(int rate) _rate(rate) void show()
const protected int _rate class
Endangered public Endangered(int pop)
_pop(pop) void count() const protected
int _pop
33
MI 2
class Whale public Swimmer, public Endangered
public Whale(int tons, int rate, int pop)
_tons(tons), Swimmer(rate), Endangered(pop)
private int _tons int main()
Whale willy(4, 15, 400) willy.show()
willy.count() return 0 What does an
instance of a Whale look like?
34
Member Ambiguity
Member function ambiguity class Swimmer
// same as before class Endangered public
void show() const class Whale public
Swimmer, public Endangered // same as
before int main() Whale willy(4, 15,
400) willy.show() // ERROR ambiguous
willy.Swimmershow() // OK
willy.Endangeredshow() // OK return 0
35
Pointer Manipulation
int main() Whale willy(4, 15, 400)
Whale wp willy wp-gtshow() // ERROR
ambiguous wp-gtSwimmershow() // OK
wp-gtEndangeredshow() // OK Swimmer sp
willy sp-gtshow() // Ambiguous?
Endangered ep willy ep-gtshow() //
Ambiguous? Swimmer sr willy
sr.show() Endangered er willy
er.show() return 0
36
Duplicate Bases
It is possible to have multiple occurrences of
the same base class in a derived class class
Asset public int _id class Equipment
public Asset public string _name class
Lift public Asset public int
_max_weight class Elevator public Lift,
public Equipment Note Data members are
public for simplicity of discussion, not because
its the right thing to do!
37
Duplicate Bases (cont.)
int main() Elevator e e._name number
1 e._max_weight 5000 e._id 1234 //
ERROR ambiguous e.Equipment_id 1234
e.Lift_id 5678 Equipment ep e
coutltltEquip ID ltlt ep-gt_id ltlt endl Lift
lp e coutltltLift ID ltlt lp-gt_id ltlt
endl Asset ap e // ERROR
ambiguous Output Equip ID 1234 Lift ID 5678
38
virtual Inheritance
This behavior is fine for some cases. But there
will be situations where it is more desirable to
only have one copy of the base class member data
of duplicate ancestors. virtual inheritance
allows only one copy of member data to be be used
for base classes that are inherited multiple
times. class Asset class Equipment
virtual public Asset class Lift public
virtual Asset class Elevator public
Equipment, public Lift
39
virtual Inheritance (cont.)
int main() // This is the same as before
Elevator e e._name number 1
e._max_weight 5000 e._id 1234 // No
longer ambiguous e.Equipment_id 1234
e.Lift_id 5678 Equipment ep e
coutltltEquip ID ltlt ep-gt_id ltlt endl Lift
lp e coutltltLift ID ltlt lp-gt_id ltlt
endl Asset ap e //No longer
ambiguous Output Equip ID 5678 Lift ID 5678
Write a Comment
User Comments (0)
About PowerShow.com