© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Chapter 1 OO using C++. Abstract Data Types Before we begin we should know how to accomplish the goal of the program We should know all the input and.
Session 07: C# OOP 4 Review of: Inheritance and Polymorphism. Static and dynamic type of an object. Abstract Classes. Interfaces. FEN AK - IT:
Inheritance, Polymorphism, and Virtual Functions
C++ Polymorphism Systems Programming. Systems Programming: Polymorphism 2   Polymorphism Examples   Relationships Among Objects in an Inheritance.
PolymorphismCS-2303, C-Term Polymorphism Hugh C. Lauer Adjunct Professor (Slides include materials from The C Programming Language, 2 nd edition,
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
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.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
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.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 11: Inheritance and Composition. Objectives In this chapter, you will: – Learn about inheritance – Learn about derived and base classes – Redefine.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Object-Oriented Programming: Polymorphism 1. OBJECTIVES What polymorphism is, how it makes programming more convenient, and how it makes systems more.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
1 Lecture OOP Course Inheritance Basics Shape.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Chapter 11: Inheritance and Composition. Introduction Two common ways to relate two classes in a meaningful way are: – Inheritance (“is-a” relationship)
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
A First Book of C++ Chapter 12 Extending Your Classes.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
C++ How to Program, 7/e.  There are cases in which it’s useful to define classes from which you never intend to instantiate any objects.  Such classes.
Learning Objectives Relationships Among Objects in an Inheritance Hierarchy. Invoking Base-class Functions from Derived Class Objects. Aiming Derived-Class.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
7. Inheritance and Polymorphism
Andy Wang Object Oriented Programming in C++ COP 3330
Inheritance and Run time Polymorphism
Inheritance & Polymorphism
Chapter 5 Classes.
Polymorphism Lec
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Chapter 11: Inheritance and Composition
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Overview of C++ Polymorphism
C++ Object Oriented 1.
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Computer Science II for Majors
Presentation transcript:

© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0

© Copyright Eliyahu Brutman Chapter 8 – More Inheritance Version 1.0

© Copyright Eliyahu Brutman More Inheritance - 3 Lets recall What we have seen so far Non-polymorphic inheritance (Object Based)  Inheritance for code reuse reasons  Reflects a relationship of Is-A  Inheritance means that the derived inherits its base class characteristics  The derived class can add to this characteristics of its own  For instance:  The layout of derived contains the layout of the base class Class person Class worker name GetName() salary CalculateSal()

© Copyright Eliyahu Brutman More Inheritance - 4 Lets recall We can invoke all inherited characteristics through the derived For instance, we can ask the worker what is his name, even though he does not implement such a method Worker w( … ); w.GetName(); The compiler resolves the call to Person::GetName() If we implement such a method at the Worker class  It will be called (resolved to Worker::GetName()) Protected access keyword has been introduced

© Copyright Eliyahu Brutman More Inheritance - 5 Lets Continue to Polymorphic Inheritance Suppose we have a container of Employees We would like to iterate over all employees, without knowing which specific kind they are, and ask them to calculate their salary (call their CalcSalary() method) Each type has its own calculation algorithm, based on different considerations Each object will invoke its relevant CalcSalary(), depending on its type Class Employee Class SalesPersonClass ExecutiveClass Administrative m_salary v. CalcSalary() m_salesm_performance

© Copyright Eliyahu Brutman More Inheritance - 6 Example We want each element in the container to call its own CalcSalary() method as a function of the real object Employee  Employee::CalcSalary() SalesPerson  SalesPerson::CalcSalary() Executive  Executive::CalcSalary() Administrative  Administrative::CalcSalary() Executive Administrative Executive Sales Person Employee* employees[100];

© Copyright Eliyahu Brutman More Inheritance - 7 Static and dynamic binding In object-oriented programming languages in most cases the variables are bound to a specific type at compile time Static binding Dynamic binding The type of the variable can change at run time Using pointers to classes related by inheritance Executive exec; Employee* emp = &exec; Can be dangerous in some cases

© Copyright Eliyahu Brutman More Inheritance - 8 Example Definition: Single name denotes objects of different classes related by inheritance Ability to manipulate derived objects using the interface defined in the base class Example: class Employee { public: void CalcSalary (); }; class SalariedEmployee :public Employee{ public: void CalcSalary (); };

© Copyright Eliyahu Brutman More Inheritance - 9 Example Employee *ep; ep = new SalariedEmployee; ep->CalcSalary(); Which function is called? The function in Employee is called To avoid that we have to declare CalcSalary() as a virtual function virtual is a special keyword

© Copyright Eliyahu Brutman More Inheritance - 10 Virtual Functions Definition: Member function prefaced by the virtual specifier. Compiler generates the code that will select the appropriate function at runtime Example: class Employee { public: virtual void CalcSalary (); }; class SalariedEmployee:public Employee{ public: virtual void CalcSalary (); }; virtual specifier needs to appear in the base class only However, typically specified also in subclusses

© Copyright Eliyahu Brutman More Inheritance - 11 Examples Employee *p0 = new Employee; Employee *p1 = new SalariedEmployee; p0->CalcSalary(); // calls Employee::CalcSalary() p1->CalcSalary(); // calls SalariedEmployee::CalcSalary() Any non-static member function except a constructor can be virtual Virtual functions can also be friends of other classes Some compilers require the class destructor to be virtual if a class contains any virtual functions

© Copyright Eliyahu Brutman More Inheritance - 12 Virtual Functions class A { public: void x() {cout<<"A:x";}; virtual void y() {cout<<"A:y";}; }; class B : public A { public: void x() {cout<<"B:x";}; virtual void y() {cout<<"B:y";}; }; int main () { B b; A *ap = &b; B *bp = &b; b.x (); // prints "B:x" b.y (); // prints "B:y" bp->x (); // prints "B:x" bp->y (); // prints "B:y" ap->x (); // prints "A:x" ap->y (); // prints "B:y" return 0; }; Only matter with pointer or reference Calls on object itself resolved statically b.y(); Look first at pointer/reference type If non-virtual there, resolve statically  ap->x(); If virtual there, resolve dynamically  ap->y(); Caller can force static resolution of a virtual function via scope operator ap->A::y(); prints “ A::y ”

© Copyright Eliyahu Brutman More Inheritance - 13 Combinations of virtual and non-virtual functions Non-virtual function can call virtual function Example: class Employee { public: void Display(); virtual void CalcSalary (); }; class SalariedEmployee:public Employee{ public: void Display(); virtual void CalcSalary (); };

© Copyright Eliyahu Brutman More Inheritance - 14 Example void Employee::Display() { CalcSalary(); }; void SalariedEmployee::Display() { CalcSalary(); }; Employee *p0 = new SalariedEmployee; p0->Display(); // calls SalariedEmployee::CalcSalary();

© Copyright Eliyahu Brutman More Inheritance - 15 Example It works the other way too class Employee { public: virtual void Display(); void CalcSalary (); }; class SalariedEmployee:public Employee{ public: virtual void Display(); void CalcSalary (); }; Employee *p0 = new SalariedEmployee; p0->Display(); // calls Employee::CalcSalary();

© Copyright Eliyahu Brutman More Inheritance - 16 Common Interface Virtual functions in the base class provide common interface for all of its derived classes Example: class Employee { public: long GetDepartment(); long GetId(); virtual void Display(); virtual void Input (); virtual void CalcSalary (); private: long id; long deptNum; };

© Copyright Eliyahu Brutman More Inheritance - 17 Example class Polygon { protected: int width, height; public: void set_values (int a, int b){ width=a; height=b; } virtual int area(); }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } };

© Copyright Eliyahu Brutman More Inheritance - 18 Example (cont.) int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout area() << endl; return 0; }

© Copyright Eliyahu Brutman More Inheritance - 19 Virtual Destructors Destructor preceded by the virtual specifier Correct destructor must be called It is recommended that any class containing virtual functions should also have a virtual destructor Example BookItem needs a separate destructor to de-allocate the storage for title class Item { public: virtual ~Item(); //... }; class BookItem { public: virtual ~BookItem(); private: char * title; };

© Copyright Eliyahu Brutman More Inheritance - 20 Pure Virtual The Employee can define this method at the base class as pure virtual : virtual int Employee::CalcSalary() = 0; Meaning, It wants all inheriting classes to implement their own implementation We cannot instantiate an object of this class – it is said to be an Abstract Class But we still can have pointers

© Copyright Eliyahu Brutman More Inheritance - 21 Example class Polygon { protected: int width, height; public: void set_values (int a, int b){ width=a; height=b; } virtual int area()=0; }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } };

© Copyright Eliyahu Brutman More Inheritance - 22 Example (cont.) int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout area() << endl; return 0; }

© Copyright Eliyahu Brutman More Inheritance - 23 Virtual Functions class A { public: virtual void x() = 0; virtual void y() = 0; }; class B : public A { public: virtual void x(); }; class C : public B { public: virtual void y(); }; int main () { A * ap = new C; ap->x (); ap->y (); delete ap; return 0; }; A is an Abstract Base Class Declares pure virtual functions (=0) Derived classes override pure virtual methods B overrides x(), C overrides y() Can ’ t instantiate class with declared or inherited pure virtual functions A and B are abstract, can create a C Can still have a pointer to an abstract class type Useful for polymorphism

© Copyright Eliyahu Brutman More Inheritance - 24 Static Binding Vs. Dynamic Binding Static Binding Function call is resolved during compile time CALL fixed value Dynamic Binding During compile time we cannot know what address to jump to It needs to be resolved during run-time Depending on the type of the actual object This information is accessed via virtual pointer Each object holds And via virtual table Each class maintains

© Copyright Eliyahu Brutman More Inheritance - 25 Dynamic Binding - Implementation Executive Administrative Executive Sales Person Executive Virtual Table Sales Person Virtual Table Executive::CalcSalary() SalesPerson::CalcSalary() Employee* employees[100];

© Copyright Eliyahu Brutman More Inheritance - 26 Summary: Tips on Polymorphism Push common code and variables up into base classes Use public inheritance for polymorphism Polymorphism depends on dynamic typing Use a base-class pointer or reference if you want polymorphism Use virtual member functions for dynamic overriding Use private inheritance only for encapsulation Use abstract base classes to declare interfaces Even though you don ’ t have to, label each virtual method (and pure virtual method) in derived classes