Upload
brandon-french
View
229
Download
0
Embed Size (px)
Citation preview
Object Oriented Programming in
C++
Chapter 6
Inheritance
IntroductionIn this section we will examine why we use inheritance base classes and derived classes protected members casting of derived class references to base class
references casting of base class pointers to derived class pointers use of member functions redefinition of base class members public, protected and private base classes direct and indirect base class classes constructors and destructors in derived classes implicit conversion relationships multiple inheritance
Why do we use Inheritance?We use inheritance because it promotes software reuse by allowing the defining of a
heirarchy of classes
• with successive refinement of behavior
• additional behavior
• restrictions on behaviour
• additional data members allows the construction of software by using existing class
libraries and tailoring them to the current situation better supports the abstraction of the essentials of the
problem
Base Classes and Derived Classes Derived classes inherit from their base class Derived classes obtain their own copies of all
the base class’s data members and member functions (albeit with restrictions)
Each instance of a derived class is also an instance of the base class (the inverse is not true)
Derived classes can themselves become base classes, allowing successive refinement of an abstraction process and of the behavior
Inheritance syntaxIf we wished to implement this inheritance pattern, given the Student base class, we might write
class Postgrad : public Student {
...};
This is called public inheritance. Protected and private inheritance are also possible but are far less common.
Post Grad StudentPost Grad Student
StudentStudent
An Inheritance Hierarchy
Elipse Rectangle PolygonBezier ArcLinePoint
Shape
1-Dimens0-Dimens 2-Dimens
Terminology
Inheritance (Derivation) - Producing new classes by inheriting methods and data from an existing class or classes
Employee
nameage
Manager
nameagelevel
Superclass
Base class
Derived class
Sub-class
Private and Protected MembersWhen we use public inheritance Private members (either data or functions) of a base class
are not accessible to derived classes, except through public member functions of the base class.
Public members of a base class are accessible to the derived class.
There is an intermediate category of access protection called protected. Protected members of the base class can only be accessed by members and friends of the base class and of any derived class.
Protected data violates data encapsulation, in that changes to the base class protected members may require changes to all derived classes.
Protected Members
notaccessible
Private
Public
Protected
Accessibleto derived
classes only
Derived Class
Constructors and Destructors in Derived Classes
A base class initialiser can be called in the derived class’s constructor, if not the default constructor will be called.
Base class constructors are called before the derived class constructor is called.
Destructors are called in the reverse order of construction, i.e. derived class before base class.
Example
class Buffer {int* ptr;int size;
public:Buffer(int sz) { ptr = new int[ size=sz]; }int& operator[](int i) { return ptr[i]; }boolean inRange(int);~Buffer() { delete [] ptr; }
};
A Derived Class
class Stack : public Buffer {int top;
public:Stack(int sz) : Buffer(sz) { top = -1; }void push(int x);int pop( );boolean empty( );boolean full( );
};
Compatibility Between Base and Derived Classes
An object of a derived class can be treated as an object of its base class.
The reverse is not true.
Example:
main(){
Stack stk(30);int i,for( i=0; i<10; +
+i)
stk.push(i);fun1(stk);fun2(stk);. . .
void fun1(Buffer bf){
for( int i=0; i<10; i++)cout << bf[i]
<< ‘ ‘ ;cout << ‘\n’ ;
}
void fun2(Stack st){
while( !st.empty() )cout <<
st.pop() << ‘ ‘ ;cout << ‘\n’ ;
}
Casting of References and Pointers
It is possible to cast a reference to a derived class to that of the base class. This is common, as it allows you to get at the base classes functionality.
It is also possible to cast a pointer of a derived class to that of the base class, and again this is common.
It is also possible to cast a pointer of a base class to that of the derived class. This is perilous (but not illegal).
Exampleclass Student{friend ostream &operator<<
(ostream &, const Student &);friend istream &operator>> (istream
&, Student &);public: Student();private: char name[30]; char degree[15];};
class Postgrad : public Student{friend ostream & operator<<
(ostream &, const Postgrad &);
friend istream & operator>> (istream &, Postgrad &);
public: Postgrad();private: char Supervisor[20]; char Thesis[20];};
Student class I/O operators
ostream &operator<< (ostream &output, const Student &s){ output << "Name : " << s.name << endl; output << "Degree : " << s.degree << endl; return output;}
istream &operator>> (istream &input, Student &s){ input >> s.name >> s.degree; return input;}
Post Grad class I/O operatorsostream &operator<< (ostream &output, const Postgrad &p){ output << static_cast<Student &> p; output << "Supervisor : " << p.Supervisor << endl; output << "Thesis Title : " << p.Thesis << endl; return output;}
istream &operator>> (istream &input, Postgrad &p){ cout << "Please input Name then Degree : "; input >> static_cast<Student &> p; cout << "Please input Supervisor and Title : " ; input >> p.Supervisor >> p.Thesis; return input;}
Test programmain(){ Student s, *s1; Postgrad p, *p1; cout << "Please input Name then Degree :"; cin >> s; cout << "You input " << s << endl; cout << "Postgraduate Student Entry\n"; cin >> p; cout << "You input\n" << p;
p1 = static_cast<Postgrad *> &s; s1 = static_cast<Student *> &p; cout << *s1; cout << *p1;
return 0;}
Casting of pointers, Casting of pointers, the first of the base the first of the base class to the derived class to the derived class, the next of the class, the next of the derived class to the derived class to the base classbase class
The OutputPlease input Name then Degree :a bYou input Name : aDegree : b
Postgraduate Student EntryPlease input Name then Degree : c dPlease input Supervisor and Title : e fYou inputName : cDegree : dSupervisor : eThesis Title : fName : cDegree : d
Name : aName : aDegree : bDegree : bSupervisor : -_n_Supervisor : -_n_Thesis Title : orland C++ - Copyright 1991 Borland Intl.Thesis Title : orland C++ - Copyright 1991 Borland Intl.
Public, Protected and Private Base Classes
private inheritance
public inheritance
protected inheritance
Base Class Specifer
public
protected
private
public in public in derived derived classclass
protected protected in derived in derived classclass
hiddenhidden
protected protected in derived in derived classclass
protected protected in derived in derived classclass
hiddenhidden
private in private in derived derived classclass
private in private in derived derived classclass
hiddenhidden
Direct and Indirect Base Classes If a class inherits explicitly from a base class, then this
is called a direct base class. If, however, a class inherits from 2 or more levels up the heirarchy, and not explicitly, this is called an indirect base class
PersonPerson Indirect Base ClassIndirect Base Class
EmployeeEmployee Direct Base ClassDirect Base Class
ManagerManager Derived ClassDerived Class
What is and is not inherited Inherited
• Member functions
• Data members Not inherited
• Constructors & Destructors
• Friendship New data members or member functions may be added Inherited functions may be redefined Inherited members cannot be removed
Inheritance
Benefits Software reusability Code sharing Consistency of interface Software components Rapid prototyping Polymorphism Information hiding
Costs Execution speed Program size Message passing
overhead Program complexity