1 / 40

Inheritance

Inheritance. CS 302 – Data Structures Section 2.4 (pp. 294-298) and Section 6.7. A. B. C. D. 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.

sricherson
Download Presentation

Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. A B C D 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 vehicle Boat Car Bicycle 2-door 4-door

  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. A B C A B D C Rules for building a class hierarchy • 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.

  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 • 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. pay attention to the syntax! Example template<class ItemType> class CountedQue: publicQueType<ItemType> {  public: CountedQue(); void Enqueue (ItemTypenewItem); void Dequeue (ItemType& item); intLengthIs() const; private: int length; };

  10. 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); }

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

  12. Polymorphism • Any client code that you write to manipulate a base class will also workwith 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” • 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) private: int front; int rear; ItemType* items; int maxQue; }; 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&);

  19. Example class DataType { // base class public: ... virtual bool operator<(DataType) const; private: StrType lastName; }; 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: class NewDataType : public DataType { // derived class public: ... bool operator<(NewDataType) const; private: StrType firstName; // new data member };

  21. Redefine “operator<“ 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; elsereturn false; } }

  22. Consider the client function: 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” and “name4” will determine which method to call!

  24. Problem again! 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; elsereturn false; } } private member of base class!

  25. Problem again … (cont’d) class DataType { // base class public: ... 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. Polymorphism revisited passed by reference, is it by coincidence? 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"; }

  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 Y class X : protected Y { ... }; • With protected inheritance, public members of Y are inherited as protected in X. 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. A B C D 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.

  33. Example • 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.

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

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

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

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

  38. Constructor: template<class ItemType> LookAheadStack <ItemType>:: LookAheadStack():StackType() { }

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

More Related