Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Inheritance CS 302 – Data Structures Section 2.4 (pp. 294-298) and Section 6.7."— Presentation transcript:

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

2 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

3 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

4 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

5 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.

6 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

7 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

8 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)

9 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!

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

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

12 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() !!

13 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”

14 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!

15 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.

16 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!

17 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.

18 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; };

19 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; }

20 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 };

21 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; }

22 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"; }

23 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!

24 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!

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

26 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).

27 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?

28 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!

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

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

31 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

32 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

33 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

34 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; };

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

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

37 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); }

38 Constructor: template LookAheadStack :: LookAheadStack():StackType() { }

39 c)Which functions and from which class should be declared as virtual?

40 The functions that should be declared as virtual are: Push from base class (i.e., StackType) Destructor from base class (i.e., StackType)


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

Similar presentations


Ads by Google