Inheritance CS 302 – Data Structures Section 2.4 (pp. 294-298) and Section 6.7.

Slides:



Advertisements
Similar presentations
Stack and Queues using Linked Structures Kruse and Ryba Ch 4.
Advertisements

Lists + CS3240, L. Grewe 1. 2 Goals Use the C++ template mechanism fr defining generic data types Implement a circular linked list Implement a linked.
Queues CS 308 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: –Elements are added at.
What is a Queue? n Logical (or ADT) level: A queue is an ordered group of homogeneous items (elements), in which new elements are added at one end (the.
Queues CS 3358 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: – Elements are added.
What is a Queue? A queue is a FIFO “first in, first out” structure.
Chapter 5 ADTs Stack and Queue. 2 Goals Describe a stack and its operations at a logical level Demonstrate the effect of stack operations using a particular.
1 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Inheritance CS 308 – Data Structures “the mechanism by which one class acquires the properties of another class” the properties of another class”
Stacks and Queues & Inheritance 2014 Spring CS32 Discussion Jungseock Joo.
Doubly-Linked Lists Same basic functions operate on list Each node has a forward and backward link: What advantages does a doubly-linked list offer? 88.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
1 expanded by J. Goetz Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Specification and Implementation Separating the specification from implementation makes it easier to modify programs. Changes in the class’s implementation.
1 C++ Plus Data Structures Nell Dale Queues ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified.
Implementing a Stack as a Linked Structure CS 308 – Data Structures.
1 Chapter 6 Object-Oriented Software Development.
Stacks CS 308 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
5 Linked Structures. 2 Definition of Stack Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Implementing a Queue as a Linked Structure CS 308 – Data Structures.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
OOP Languages: Java vs C++
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Data Structures Lecture-12 : STL Azhar Maqsood NUST Institute of Information Technology (NIIT)
What is a Stack? n Logical (or ADT) level: A stack is an ordered group of homogeneous items in which the removal and addition of items can take place only.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Chapter 10 Inheritance and Polymorphism
1 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of.
Queues CS 302 – Data Structures Sections 5.3 and 5.4.
Stacks CS 302 – Data Structures Sections 5.1, 5.2, 6.1, 6.5.
Chapter 5 ADTs Stack and Queue. Stacks of Coins and Bills.
Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Chapter -6 Polymorphism
What happens... l When a function is called that uses pass by value for a class object like our dynamically linked stack? StackType MakeEmpty Pop Push.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
1 Data Structures and Algorithms Stacks and Queues.
1 C++ Plus Data Structures Nell Dale Chapter 5 Linked Structures Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
Inheritance in C++ Bryce Boe 2012/08/28 CS32, Summer 2012 B.
CSI 1340 Introduction to Computer Science II Chapter 6 Lists Plus.
Chapter 5 (Part 1) ADT Stack 1 Fall Stacks TOP OF THE STACK.
1 C++ Plus Data Structures Abstract Data Types Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Queues.
Inheritance and Polymorphism
C++ Plus Data Structures
Stack and Queue APURBO DATTA.
Advanced C++ Topics Chapter 8.
Chapter 5 ADTs Stack and Queue.
C++ Plus Data Structures
Chapter 5 ADTs Stack and Queue Fall 2013 Yanjun Li CS2200.
Chapter 8: Class Relationships
CIS 199 Final Review.
C++ Plus Data Structures
CSI 1340 Introduction to Computer Science II
Queues.
Computer Science II for Majors
Presentation transcript:

Inheritance CS 302 – Data Structures Section 2.4 (pp ) and Section 6.7

Inheritance hierarchy - example Concepts at higher levels are more general Concepts at lower levels are more specific (i.e., inherit properties of concepts at higher levels) Vehicle Wheeled vehicleBoat CarBicycle 4-door2-door A B C D

C++ and inheritance “The mechanism by which one class acquires the properties (i.e., data and operations) of another class.“ Base Class (or super-class): the class being inherited from. Derived Class (or sub-class): the class that inherits. A B

Rules for building a class hierarchy can also serve A derived class can also serve as a base class for new classes. depth of inheritance There is no limit on the depth of inheritance allowed in C++ (as far as it is within the limits of your compiler). more than one It is possible for a class to be a base class for more than one derived class. B A C A B C D

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.

Advantages three When a class inherits from another class, there are three main 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

Example Define a new class CountedQue from QueType such that it has a new data member (length) that holds the number of items in the queue

Derived class definition The definition (.h file) of the derived class should include: –New private members –New member functions –Modified member functions –Constructor (always), destructor (if needed)

Example template CountedQuepublic class CountedQue : public QueType { public: CountedQue(); void Enqueue (ItemType newItem); void Dequeue (ItemType& item); int LengthIs() const; private: int length; }; pay attention to the syntax!

Modifying class behavior template void CountedQue ::Enqueue(ItemType newItem) { length++; QueType ::Enqueue(newItem); } template void CountedQue ::Dequeue(ItemType& item) { length--; QueType ::Dequeue(item); }

Extending class behavior template int CountedQue ::LengthIs() const { return length; } // class constructor template CountedQue ::CountedQue() : QueType () { length=0; } pay attention to the syntax!

Polymorphism will also work Any client code that you write to manipulate a base class will also work with any class derived from the base class. //client function void Test(QueType& q, ItemType item) { q.Enqueue(item);.... } Any object of a class derived from QueType can be passed as a parameter to Test() !!

Polymorphism (cont’d) General rule for passing objects to a function in C++: “the actual parameters and their corresponding formal parameters must be of the same type” “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”

Problem! // client function void Test(QueType& q, ItemType item) { q.Enqueue(item);.... } Which Enqueue() should be called? This information is not available at compile time!

Static vs. dynamic binding Static Binding: the determination of which fynction to call at compile time. Dynamic Binding: the determination of which function to call at run time.

Static vs. dynamic binding (cont’d) Static Binding: the data type of the formal parameter determines which Enqueue will be called! Dynamic Binding: the data type of the actual parameter determines which Enqueue will be called!

Virtual Functions C++ uses virtual functions to implement dynamic binding. The keyword virtual should appear before the corresponding function declaration in the definition of the base class. Using “virtual”, the compiler generates extra code to implement dynamic binding.

QueueType (base class) template class QueueType { public: QueueType(int); QueueType(); ~QueueType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; virtual virtual void Enqueue(ItemType); virtual virtual void Dequeue(ItemType&); private: int front; int rear; ItemType* items; int maxQue; };

Example DataType class DataType { // base class public:... operator virtual bool operator<(DataType) const; private: StrType lastName; }; DataTypeoperato bool DataType::operator<(DataType item) const { int result; result = strcmp(lastName, item.lastName); if(result < 0) return true; else return false; }

Now, derive a new class from it: NewDataTypeDataType class NewDataType : public DataType { // derived class public:... bool operator<(NewDataType) const; private: StrType firstName; // new data member };

Redefine “operator<“ NewDataTypeNewDataType bool NewDataType::operator<(NewDataType 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; }

Consider the client function: DataTypeDataType void PrintResult(DataType& first, DataType& second) { if(first < second) // i.e., 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: DataType name1, name2; NewDataType name3, name4;.... PrintResult(name1, name2); PrintResult(name3, name4); The types of “name2”“name4” “name2” and “name4” will determine which method to call!

Problem again! NewDataTypeNewDataType bool NewDataType::operator<(NewDataType 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; } private member of base class!

Problem again … (cont’d) DataType class DataType { // base class public:... operator virtual bool operator<(DataType) const; private: StrType lastName; }; protected:

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 (i.e., same as private).

DataTypeDataType void PrintResult(DataType& first, DataType& second) { if(first < second) // i.e., first.operator<(second) cout << "First comes before second"; else cout << "First does not come before second"; } Polymorphism revisited passed by reference, is it by coincidence?

Slicing Problem If the object from derived class is passed by reference, everything works fine. If the object from derived class is passed by value, only the sub-object of the base class is passed to the function!

Public, Protected and Private Inheritance class X : public Y {... }; With public inheritance, public members of Y are inherited as public in X. Y X

Public, Protected and Private Inheritance class X : protected Y {... }; With protected inheritance, public members of Y are inherited as protected in X. Y X

Public, Protected and Private Inheritance class X : private Y {... }; With private inheritance, public members of Y are inherited as private in X. Default inheritance: private Y X

Constructors and destructors Cannot override a base class constructor with a derived class constructor. –i.e., derived class constructor need to call base class constructor first Base class destructors should be declared virtual. Virtual destructors are called in reverse order from that of the constructors. A B C D

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 struct NodeType; template StackType class StackType { public: StackType(); ~StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push (ItemType); void Pop(ItemType&); private: NodeType * topPtr; };

Example 4 (cont’d) template LookAheadStackStackType class LookAheadStack : public StackType { public: void Push(ItemType); LookAheadStack(); ~LookAheadStack(); };

b)Implement the new push function and the derived class’ constructor.

template void LookAheadStack ::Push(ItemType newItem) { ItemType item; if ( !StackType ::IsEmpty() ) { StackType ::Pop(item); StackType ::Push(item); if (item != newItem) StackType ::Push(newItem); } else StackType ::Push(newItem); }

Constructor: template LookAheadStack :: 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 (i.e., StackType) Destructor from base class (i.e., StackType)