Upload
toyah
View
17
Download
0
Embed Size (px)
DESCRIPTION
Inheritance Basics Fall 2008 . Dr. David A. Gaitros [email protected]. The Reason for Inheritance . “Why write the same code twice?” - PowerPoint PPT Presentation
Citation preview
Inheritance BasicsFall 2008
Dr. David A. [email protected]
The Reason for Inheritance
“Why write the same code twice?” This sums up the reason for inheritance
quite nicely. Take the example of an employee database. There are many kinds of employees which have different attributes (data points) that need to be tracked for each one.
However, there are some attributes that are common to ALL employees. This code should be written and “inherited” by those modules that handle the specifics for each type of employee.
Inheritance
• Examples of relationshipsA class called Geometric_Objects could derive
classes like Circle, Square, and LineA class called Sport could derive classes like
Football, Baseball, and SoccerA class called BankAccount could derive classes
such as Checking, Savings, and DebitA class called vehicle could derive classes called
Car, Train, Bus, Motorcycle, and AirplaneWe could use the Car class as a base class and
derive other classes such as Ford, Toyota, Buick, Honda, etc.
Inheritance
Declaring a Derived Class“When we say that some class D is a
derived of some other class B, we are saying that class D has all of the features of class B but with some extra. Class B is called the base class.
//class derivedclassname: public baseclassname//class Sport{ ….}class Football: public Sport{ …}
Inheritance
• Layers of Inheritance
class Vehicle { … }class Car: public Vehicle { …}class Honda: public Car { …}
Protection Levels
• public – Any member that is public can be directly accessed by name from anywhere. Poor practice to have data values with public access.
• private – Any member that is private can only be accessed directly only by the class in which it is declared.
• protected – Any member that is protected can be access directlry by the class in which it was declared and any classes that are derived.