SlideShare a Scribd company logo
1 of 33
Inheritance
CS 308 – Data Structures
“the mechanism by which one class acquires
the properties of another class”
Arrange concepts into an inheritance
hierarchy
• Concepts at higher levels are more general
• Concepts at lower levels are more specific (inherit
properties of concepts at higher levels)
Vehicle
Wheeled vehicle Boat
Car Bicycle
4-door
2-door
C++ and inheritance
• The language mechanism by which one
class acquires the properties (data and
operations) of another class
• Base Class (or superclass): the class being
inherited from
• Derived Class (or subclass): the class that
inherits
Advantages of inheritance
• When a class inherits from another class,
there are three benefits:
• (1) You can reuse the methods and data of
the existing class
(2) You can extend the existing class by
adding new data and new methods
(3) You can modify the existing class by
overloading its methods with your own
implementations
Deriving One Class from Another
Deriving One Class from Another (cont’d)
• Define a new class CountedQue from QueType
such that it has a new data member (length) that
records the number of items in the queue
template<class ItemType>
class CountedQue : public QueType<ItemType> {
public:
CountedQue();
void Enqueue (ItemType newItem);
void Dequeue (ItemType& item);
int LengthIs() const;
private:
int length;
};
Inheritance and accessibility
• A class inherits the behavior of another
class and enhances it in some way
• Inheritance does not mean inheriting access
to another class’ private members
Rules for building a class
hierarchy
• Derived classes are special cases of base classes
• A derived class can also serve as a base class for
new classes.
• There is no limit on the depth of inheritance
allowed in C++ (as far as it is within the limits of
your compiler)
• It is possible for a class to be a base class for more
than one derived class
Modifying class behavior
template<class ItemType>
void CountedQue<ItemType>::Enqueue(ItemType newItem)
{
length++;
QueType<ItemType>::Enqueue(newItem);
}
template<class ItemType>
void CountedQue<ItemType>::Dequeue(ItemType& item)
{
length--;
QueType<ItemType>::Dequeue(item);
}
template<class ItemType>
int CountedQue<ItemType>::LengthIs() const
{
return length;
}
// class constructor
template<class ItemType>
CountedQue<ItemType>::CountedQue() : QueType<ItemType>()
{
length=0;
}
Polymorphism
• Any code you write to manipulate a base class will
also work with any class derived from the base class.
• C++ general rule for passing objects to a function:
“the actual parameters and their corresponding formal
parameters must be of the same type”
• With inheritance, C++ relaxes this rule:
“the type of the actual parameter can be a class derived
from the class of the formal parameter”
An example
template<class ItemType>
void Test(QueType& q, ItemType item)
{
q.Enqueue(item);
....
}
• Any object of a class derived from QueType can
be passed to the function !!
• Which Enqueue() function should be used? (the
compiler does not know that at compile time)
Static vs. dynamic binding
• Static Binding: the determination of which method
to call at compile time
• Dynamic Binding: the determination of which
method to call at run time
Virtual Functions
• C++ uses virtual functions to implement run-
time binding.
• To force the compiler to generate code that
guarantees dynamic binding, the word virtual
should appear before the function declaration
in the definition of the base class.
Queue Implementation
template<class ItemType>
class QueueType {
public:
QueueType(int);
QueueType();
~QueueType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
virtual void Enqueue(ItemType);
virtual void Dequeue(ItemType&);
private:
int front;
int rear;
ItemType* items;
int maxQue;
};
• Rules for static/dynamic binding:
1) If the member function of the base class is not
a virtual function, the type of the formal
parameter determines which function to call.
2) If the member function of the base class is a
virtual function, the type of the actual
parameter determines which function to call.
Virtual Functions (cont.)
An example
class ItemType {
public:
...
virtual bool operator<(ItemType) const;
private: protected:
StrType lastName;
};
bool ItemType::operator<(ItemType item) const
{
int result;
result = strcmp(lastName, item.lastName);
if(result < 0)
return true;
else
return false;
}
Let's derive a new class from it:
class NewItemType : public ItemType {
public:
...
bool operator<(NewItemType) const;
private:
StrType firstName;
};
Let's derive a new class from it: (cont.)
bool NewItemType::operator<(NewItemType item) const
{
int result;
result = strcmp(lastName, item.lastName);
if(result < 0)
return true;
else if(result > 0)
return false;
else { // same last name
result = strcmp(firstName, item.firstName);
if(result < 0)
return true;
else
return false;
}
}
Let's assume that the client program
includes the following function:
void PrintResult(ItemType& first, ItemType& second)
{
if(first < second) // first.operator<(second)
cout << "First comes before second";
else
cout << "First does not come before second";
}
Let's assume that the client program
executes the following code:
ItemType item1, item2;
NewItemType item3, item4;
....
PrintResult(item1, item2);
PrintResult(item3, item4);
Protected class members
• Derived classes cannot access the private
data of the base class
• Declaring methods and data of the base
class as protected (instead of private) allows
derived classes to access them
• Objects outside the class, however, cannot
access them (same as private)
Warning: call by reference
vs. call by value
• If the object of the derived class is passed by
reference, everything works fine.
• If the object of the derived class is passed by
value, only the sub-object of the base class is
passed to the function (slicing problem)!!
Protected and Private Inheritance
class X : protected Y {
...
};
• With protected inheritance, public and protected
members of Y become protected in X (i.e., classes
derived from X inherit the public members of Y as
protected)
• With private inheritance, public and protected
members of Y become private in X (i.e., classes
derived from X inherit the public members of Y as
private)
• Default inheritance: private
Y
X
Constructors and destructors
• You cannot override a base class constructor with
a derived class constructor (rather, the derived
class constructor calls the base class constructor
first)
• All base class destructors should be declared
virtual
• Virtual destructors are called in reverse order from
the constructors for derived class objects
Multiple Inheritance
• Derived classes can inherit from more than
one base classes
X
Y
Z
(base for Y)
(base for Z)
Define a new class LookAheadStack that
is derived from class StackType.
(1) A look-ahead stack differs from the standard stack
only in the push operation.
(2) An item is added to the stack by the push method
only if its different from the top stack element.
Example
template<class ItemType>
struct NodeType;
template<class ItemType>
class StackType {
public:
StackType();
~StackType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Push (ItemType);
void Pop(ItemType&);
private:
NodeType<ItemType>* topPtr;
};
template<class ItemType>
class LookAheadStack : public StackType<ItemType>
{
public:
void Push(ItemType);
LookAheadStack();
~LookAheadStack();
};
b) Implement the new push function and the
derived class’ constructor.
template<class ItemType>
void LookAheadStack <ItemType>::Push(ItemType newItem)
{
ItemType item;
if ( !StackType<ItemType>::IsEmpty() ) {
StackType<ItemType>::Pop(item);
StackType<ItemType>::Push(item);
if (item != newItem)
StackType<ItemType>::Push(newItem);
}
else
StackType<ItemType>::Push(newItem);
}
Constructor:
template<class ItemType>
LookAheadStack <ItemType>:: LookAheadStack():StackType()
{
}
c) Which functions and from which class
should be declared as virtual?
The functions that should be declared as
virtual are:
Push from base class (StackType)
Destructor from base class (StackType)
Exercises
• 18-21, 23

More Related Content

Similar to Inheritance.ppt

Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceKuntal Bhowmick
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptxGopalNarayan7
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in javaAtul Sehdev
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.pptKhizar40
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 

Similar to Inheritance.ppt (20)

unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Chap08
Chap08Chap08
Chap08
 
Online CPP Homework Help
Online CPP Homework HelpOnline CPP Homework Help
Online CPP Homework Help
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
Constructor
ConstructorConstructor
Constructor
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Inheritance
Inheritance Inheritance
Inheritance
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
 
Python3
Python3Python3
Python3
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 

Recently uploaded

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 

Recently uploaded (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 

Inheritance.ppt

  • 1. Inheritance CS 308 – Data Structures “the mechanism by which one class acquires the properties of another class”
  • 2. Arrange concepts into an inheritance hierarchy • Concepts at higher levels are more general • Concepts at lower levels are more specific (inherit properties of concepts at higher levels) Vehicle Wheeled vehicle Boat Car Bicycle 4-door 2-door
  • 3. C++ and inheritance • The language mechanism by which one class acquires the properties (data and operations) of another class • Base Class (or superclass): the class being inherited from • Derived Class (or subclass): the class that inherits
  • 4. Advantages of inheritance • When a class inherits from another class, there are three benefits: • (1) You can reuse the methods and data of the existing class (2) You can extend the existing class by adding new data and new methods (3) You can modify the existing class by overloading its methods with your own implementations
  • 5. Deriving One Class from Another
  • 6. Deriving One Class from Another (cont’d) • Define a new class CountedQue from QueType such that it has a new data member (length) that records the number of items in the queue template<class ItemType> class CountedQue : public QueType<ItemType> { public: CountedQue(); void Enqueue (ItemType newItem); void Dequeue (ItemType& item); int LengthIs() const; private: int length; };
  • 7. Inheritance and accessibility • A class inherits the behavior of another class and enhances it in some way • Inheritance does not mean inheriting access to another class’ private members
  • 8. Rules for building a class hierarchy • Derived classes are special cases of base classes • A derived class can also serve as a base class for new classes. • There is no limit on the depth of inheritance allowed in C++ (as far as it is within the limits of your compiler) • It is possible for a class to be a base class for more than one derived class
  • 9. Modifying class behavior template<class ItemType> void CountedQue<ItemType>::Enqueue(ItemType newItem) { length++; QueType<ItemType>::Enqueue(newItem); } template<class ItemType> void CountedQue<ItemType>::Dequeue(ItemType& item) { length--; QueType<ItemType>::Dequeue(item); } template<class ItemType> int CountedQue<ItemType>::LengthIs() const { return length; } // class constructor template<class ItemType> CountedQue<ItemType>::CountedQue() : QueType<ItemType>() { length=0; }
  • 10. Polymorphism • Any code you write to manipulate a base class will also work with any class derived from the base class. • C++ general rule for passing objects to a function: “the actual parameters and their corresponding formal parameters must be of the same type” • With inheritance, C++ relaxes this rule: “the type of the actual parameter can be a class derived from the class of the formal parameter”
  • 11. An example template<class ItemType> void Test(QueType& q, ItemType item) { q.Enqueue(item); .... } • Any object of a class derived from QueType can be passed to the function !! • Which Enqueue() function should be used? (the compiler does not know that at compile time)
  • 12. Static vs. dynamic binding • Static Binding: the determination of which method to call at compile time • Dynamic Binding: the determination of which method to call at run time
  • 13. Virtual Functions • C++ uses virtual functions to implement run- time binding. • To force the compiler to generate code that guarantees dynamic binding, the word virtual should appear before the function declaration in the definition of the base class.
  • 14. Queue Implementation template<class ItemType> class QueueType { public: QueueType(int); QueueType(); ~QueueType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; virtual void Enqueue(ItemType); virtual void Dequeue(ItemType&); private: int front; int rear; ItemType* items; int maxQue; };
  • 15. • Rules for static/dynamic binding: 1) If the member function of the base class is not a virtual function, the type of the formal parameter determines which function to call. 2) If the member function of the base class is a virtual function, the type of the actual parameter determines which function to call. Virtual Functions (cont.)
  • 16. An example class ItemType { public: ... virtual bool operator<(ItemType) const; private: protected: StrType lastName; }; bool ItemType::operator<(ItemType item) const { int result; result = strcmp(lastName, item.lastName); if(result < 0) return true; else return false; }
  • 17. Let's derive a new class from it: class NewItemType : public ItemType { public: ... bool operator<(NewItemType) const; private: StrType firstName; };
  • 18. Let's derive a new class from it: (cont.) bool NewItemType::operator<(NewItemType item) const { int result; result = strcmp(lastName, item.lastName); if(result < 0) return true; else if(result > 0) return false; else { // same last name result = strcmp(firstName, item.firstName); if(result < 0) return true; else return false; } }
  • 19. Let's assume that the client program includes the following function: void PrintResult(ItemType& first, ItemType& second) { if(first < second) // first.operator<(second) cout << "First comes before second"; else cout << "First does not come before second"; }
  • 20. Let's assume that the client program executes the following code: ItemType item1, item2; NewItemType item3, item4; .... PrintResult(item1, item2); PrintResult(item3, item4);
  • 21. Protected class members • Derived classes cannot access the private data of the base class • Declaring methods and data of the base class as protected (instead of private) allows derived classes to access them • Objects outside the class, however, cannot access them (same as private)
  • 22. Warning: call by reference vs. call by value • If the object of the derived class is passed by reference, everything works fine. • If the object of the derived class is passed by value, only the sub-object of the base class is passed to the function (slicing problem)!!
  • 23. Protected and Private Inheritance class X : protected Y { ... }; • With protected inheritance, public and protected members of Y become protected in X (i.e., classes derived from X inherit the public members of Y as protected) • With private inheritance, public and protected members of Y become private in X (i.e., classes derived from X inherit the public members of Y as private) • Default inheritance: private Y X
  • 24. Constructors and destructors • You cannot override a base class constructor with a derived class constructor (rather, the derived class constructor calls the base class constructor first) • All base class destructors should be declared virtual • Virtual destructors are called in reverse order from the constructors for derived class objects
  • 25. Multiple Inheritance • Derived classes can inherit from more than one base classes X Y Z (base for Y) (base for Z)
  • 26. Define a new class LookAheadStack that is derived from class StackType. (1) A look-ahead stack differs from the standard stack only in the push operation. (2) An item is added to the stack by the push method only if its different from the top stack element. Example
  • 27. template<class ItemType> struct NodeType; template<class ItemType> class StackType { public: StackType(); ~StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push (ItemType); void Pop(ItemType&); private: NodeType<ItemType>* topPtr; };
  • 28. template<class ItemType> class LookAheadStack : public StackType<ItemType> { public: void Push(ItemType); LookAheadStack(); ~LookAheadStack(); };
  • 29. b) Implement the new push function and the derived class’ constructor.
  • 30. template<class ItemType> void LookAheadStack <ItemType>::Push(ItemType newItem) { ItemType item; if ( !StackType<ItemType>::IsEmpty() ) { StackType<ItemType>::Pop(item); StackType<ItemType>::Push(item); if (item != newItem) StackType<ItemType>::Push(newItem); } else StackType<ItemType>::Push(newItem); } Constructor: template<class ItemType> LookAheadStack <ItemType>:: LookAheadStack():StackType() { }
  • 31. c) Which functions and from which class should be declared as virtual?
  • 32. The functions that should be declared as virtual are: Push from base class (StackType) Destructor from base class (StackType)