inheritance1 inheritance software re-use with derived classes
Post on 19-Dec-2015
216 views
TRANSCRIPT
inheritance 2
Inheritance
• Object-oriented languages allow new classes to acquire properties from an existing class - this is known as inheritance
• Original class is called the base or parent class, or the superclass
• The new, slightly different class is the derived or child class, or the subclass
inheritance 3
Derived classes
• A derived class contains all members and functions of the base class
• The subclass inherits these members, along with their access characteristics
• The declaration of the child class determines how these access characteristics are manifested in the child class
inheritance 4
Derived class declaration
• In the declaration of the child class, the parent class is listed as either public or private; for example:class Set : public Bag– With this declaration, public members of Bag
are inherited as public members of Set– private members are inherited, but can be
accessed only through inherited functions
inheritance 5
Derived class declaration
• A derived class can also be declared with a private base class:class Set : private Bag– public members of Bag are inherited as private
members of Set– private members of Bag are accessible only
through Bag member functions
inheritance 6
Protected class members
• If a base class member is declared as protected, rather than public or private, that member is directly accessible by any class derived from the base
• Protected members act just like private members in terms of access by non-member functions, except for members of derived classes
inheritance 7
Example of inheritance in action
• We will define two classes, Point and Circle
• Circle inherits Point members and adds members of its own
• The base class (Point) data members are declared protected, rather than private, enabling direct access by the derived class (Circle)
inheritance 8
Base Class Declaration
class Point{ public:
Point (double a=0.0, double b=0.0);void setPoint(double a, double b);double getX()const {return x;}double getY()const {return y;}friend ostream& operator << (ostream &o, const Point &p);
protected:double x;double y;
};
inheritance 9
Base class function definitionsPoint::Point (double a, double b) void Point::setPoint(double a, double b){ {
x = a; x = a;y = b; y = b;
} }
ostream & operator << (ostream &o, const Point &p){
o << “[” << p.x << “, ” << p.y << “]”;return o;
}
inheritance 10
Child class definition
class Circle : public Point{ public:
Circle (double r =0.0, double x=0, double y=0);void setRadius(double r) {radius = r;}double getRadius () const {return radius;}double area () const {return radius*radius*3.14159;}friend ostream& operator << (ostream &o, const Circle &c);
protected:double radius;
};
inheritance 11
Circle constructor
Circle::Circle(double r, double x, double y): Point(x,y)
{radius = r;
}
The line preceding the function’s begin bracket :Point (x,y)
indicates a call to the constructor of the parent class
This is not actually a separate line of code, but part of the function’s heading
inheritance 12
Circle friend functionostream& operator << (ostream &o, const Circle &c){
o << “Center = [” << c.x << “, ” << c.y << “]” << “ Radius = ” << c.radius;return o;
}
Members x and y of parent class Point are accessible tochild class Circle because of protected status
Members x and y are members of the Circle object; in otherwords, there is a Point in every Circle
inheritance 13
The “is-a” relationship
• The Point/Circle example is atypical of the way inheritance is usually used
• Inheritance usually involves creating a generic base class, then deriving several child classes from it
• The relationship of the child to the parent is usually described using the phrase “is a” -- we say a derived class object is a parent class object
inheritance 14
The “is-a” relationship• For example, your textbook describes a
generic Clock class, then creates the derived class CuckooClock
• It is natural to say “a CuckooClock is a Clock” - meaning a cuckoo clock is a kind of clock
• It wouldn’t be too much of a stretch to derive other Clock types - alarm clock, 24-hour clock, etc.
inheritance 15
Using a derived class
• Derived class objects can call base class member functions as if they were member functions of the derived class
• An object of the derived class may be used in place of a base class object - for example, if a function takes a base class object as a parameter, a derived class object may be substituted
inheritance 16
Derived classes & assignment
• Assignments are allowed form a derived class to a base class if the base class is public
• However, a base class object cannot be used as if it were an object of the derived class - so you can’t assign a base class object to a derived class variable
inheritance 17
Inheritance & Overriding
• A derived class inherits all members of the base class, but often a derived object needs to perform a particular operation a different way than that defined in an inherited function
• When a new function body is provided for an inherited member function within a derived class, the function is overridden
inheritance 18
Inheritance & Overriding
• Sometimes overriding a function involves adding functionality, rather than simply replacing an original base class function
• When this is the case, the overriding function can call the base class function as its first action, then proceed with additional operations
inheritance 19
Exampleint Clock24::get_hour() const // overrides inherited function{
int ohr;ohr = Clock::get_hour() // call to overridden functionif (is_morning()){
if (ohr == 12)return 0;
elsereturn ohr;
}etc.
inheritance 20
Using inheritance with ADTs
• Throughout the semester, we have studied various container classes
• In many ways, one container is very much like another; inheritance can be used to derive many different types of containers by placing common characteristics in a base class
inheritance 21
Example: Set derived from Bag
• Both Bags and Sets contain unordered collection of elements
• The basic difference between them is that all elements in a Set must be unique
• We can create a Set class by inheriting from Bag, and overriding the insert function to eliminate insertion of duplicates
inheritance 22
Example: Generic List Class
• Suppose you are provided with a generic ADT to hold an ordered list of items
• The data part of the List class is unknown to you, but you are given a set of member functions and a description of their actions, as shown on the slides that follow
inheritance 23
List member functions
List()// postcondition: initializes an empty Listbool is_item() const// postcondition: returns true if there is a valid current// item; false if there is no valid current itemItem current() const// precondition: is_item returns true// postcondition: returns current List itemvoid start()// postconditon: first item on List becomes current item;// if list is empty, there is no current item
inheritance 24
List member functions
void advance()// precondition: is_item returns true// postcondition: if current item was the last on List, there is// now no current item; otherwise, the new current item is the// one immediately following the original current itemvoid insert (const Item &entry)// postcondition: a new copy of entry has been inserted before// the current item; if no current item existed, entry was inserted// at the front of the List. Item containing entry is now the// current item
inheritance 25
List member functions
void attach (const Item &entry)// postcondition: a new copy of enty has been inserted in list// after the current item; if there was no current item, entry was// inserted at the end of the list. Item containing entry is now the// current itemvoid remove_current()// precondition: is_item returns true// postcondition: current item has been removed; item following// current (if one existed) is now current itemsize_t size() const// postcondition: returns count of items in List
inheritance 26
Deriving Stack from List
• Stack is defined by its push and pop functions, respectively inserting and removing items from the same end of the structure
• Because List has many functions that won’t (and shouldn’t) be used directly by users of Stack code, List is inherited as a private base class
inheritance 27
Stack class definitiontemplate <class Item>class Stack : private List<Item>{
public:void push(const Item
&entry);Item pop();Item peek() const;List<Item>::size;
// changes inherited private function size to public// Stack function available to Stack user - this is an// example of exempting a member from private base// class
bool is_empty() const {return size() == 0;}};
inheritance 28
Stack member functions
template <class Item>void push (const Item &entry){
insert(entry);}
template <class Item>Item pop(){
Item answer;assert(size() > 0);answer = current();remove_current();return answer;
}
template <class Item>Item peek(){
assert (size() > 0);return current();
}
inheritance 29
Deriving Queue from List
• A child queue class could be derived from List in a similar fashion
• List would be inherited as a private base class, and queue functions enqueue and dequeue would be defined using inherited private functions from List