Learning Objectives Relationships Among Objects in an Inheritance Hierarchy. Invoking Base-class Functions from Derived Class Objects. Aiming Derived-Class.

Slides:



Advertisements
Similar presentations
2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
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,
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Virtual Functions Fall 2008 Dr. David A. Gaitros
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Chapter 12: Adding Functionality to Your 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.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Cpt S 122 – Data Structures Polymorphism
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Object-Oriented Programming: Polymorphism 1. OBJECTIVES What polymorphism is, how it makes programming more convenient, and how it makes systems more.
Chapter 15 Polymorphism and Virtual Functions. Learning Objectives Virtual Function Basics – Late binding – Implementing virtual functions – When to use.
Slide 1 Polymorphism and Virtual Functions. Slide 2 Learning Objectives  Virtual Function Basics  Late binding  Implementing virtual functions  When.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Object Oriented Concepts
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Object Oriented Concepts Classes II. Object Oriented concepts Encapsulation Composition Inheritance Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy Invoking Superclass Methods.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Polymorphism and Virtual Functions. Motivation Polymorphism is one of the fundamental mechanisms offered by OOP, and it is directly related to inheritance.
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.
Inheritance. Lecture contents Inheritance Class hierarchy Types of Inheritance Derived and Base classes derived class constructors protected access identifier.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Java Programming Dr. Randy Kaplan. Abstract Classes and Methods.
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.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Object Oriented Programming
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Overview of C++ Polymorphism
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Problems with assn 3? Discuss at your team meeting tonight.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object-Oriented Programming: Inheritance and Polymorphism.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Object-Oriented Programming: Polymorphism Chapter 10.
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.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
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.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Virtual Function and Polymorphism
Polymorphism and Virtual Functions
7. Inheritance and Polymorphism
Polymorphism.
Polymorphism & Virtual Functions
Lecture 23 Polymorphism Richard Gesick.
Learning Objectives Inheritance Virtual Function.
Inheritance, Polymorphism, and Virtual Functions
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Object-Oriented Programming: Inheritance and Polymorphism
Fundaments of Game Design
Chapter 8: Class Relationships
VIRTUAL FUNCTIONS RITIKA SHARMA.
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.
Presentation transcript:

Learning Objectives Relationships Among Objects in an Inheritance Hierarchy. Invoking Base-class Functions from Derived Class Objects. Aiming Derived-Class Pointers at Base Class Objects. Derived-Class Member-Function calls via Base-Class Pointers. Virtual Functions. Abstract classes and pure virtual functions.

polymorphism The word Polymorphism means many forms. In programming this word is meant to reuse the single code multiple times. Its obvious that when we do inheritance between two classes, all the methods and properties of the first class are derived to the other class so that this becomes the child class which adobes all the functionality of base class. It can also possesses its own separate methods. But there is a big problem in inheriting the second class to the first class as it adobes all the methods same as the base class has, which means that after inheritance both(base class& child class) have the methods of same name

Con.. Example: ___Base Class___ public class fish { public void eat() { console.writeline("fish eat"); } public void swim() { console.writeline("fish swim"); } }

Cont… __Derived Class______ class Dolphen:fish { public void eat() { console.writeline("fish eat"); } public void swim() { console.writeline("fish swim"); } }

Cont… when we Inherit two classes, all the methods with the same name and same body are aboded by the derived class.Both methods have the same name but if we change the body of the second method then it makes Compiler disturb whether to compile base class method or derived class's method first... each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations.

Cont… ____Base Class___ public class fish { public void eat() { console.writeline("fish eat"); } public void swim() { console.writeline("fish swim"); } }

Cont… ______Derived Class______ class Dolphin:fish { public void eat() { console.writeline("Dolphin can eat"); } public void swim() { console.writeline("Dolphin can swim"); } } In this example we have changed the body of the methods of Derived class.Now this will make the Compiler disturb to compile which method first, because they both have same name but different bodies.

Cont… Polymorphism is used in changing the name of the methods of both base & derived class. Infect is done by adding the "virtual" keyword before the base class method, and the "override" keyword before the derived class method. As shown in this exmple: ____Base Class___ public class fish { public virtual void eat() { Console.WriteLine("fish eat"); } public virtual void swim() { Console.WriteLine("fish swim"); } }

Cont… ______Derived Class______ class Dolphin : fish { public override void eat() { Console.WriteLine("Dolphin can eat"); } public override void swim() { Console.WriteLine("Dolphin can swim"); } } This is actually the Polymorphism in which virtual keyword with the base class method and override keyword with the derived class method. It helps the compiler to select the method to be executed.

Cont.. class Program { public class fish { public virtual void eat() { } public virtual void swim() { } public virtual void dive() {} } public class Dolphin : fish }

Cont.. { public override void eat() { Console.WriteLine("Dolphin eats Plants"); } public override void swim() { Console.WriteLine("Dolphin swims quickly"); } public override void dive() { Console.WriteLine("Dolphin dive deeply "); } public void dance() { Console.WriteLine("Dolphin can Dance"); } }

Cont.. public class Shark : fish { public override void eat() { Console.WriteLine("Shark eats dead animal"); } public override void swim() { Console.WriteLine("Sharks swim fastest than Dolphin"); } public override void dive() { Console.WriteLine("Sharks Dive deeper than Dolphin"); } public void kill() { Console.WriteLine("Shark kills Others"); } }

Cont.. static void Main(string[] args) { Dolphin D = new Dolphin(); D.dance(); D.dive(); D.eat(); D.swim(); Shark S = new Shark(); S.kill(); S.dive(); S.eat(); S.swim(); Console.ReadLine(); }

Cont… Polymorphism –Associating many meanings to one function –Virtual functions provide this capability –Fundamental principle of object-oriented programming! Virtual - Existing in "essence" though not in fact Virtual Function Can be "used" before it’s "defined“ Tells compiler: –"Don’t know how function is implemented" –"Wait until used in program" –"Then get implementation from object instance" Called late binding or dynamic binding - Virtual functions implement late binding Define a method as virtual, and the subclass method overrides the base class method E.g., class Shape { public: virtual void Rotate(); virtual void Draw(); …} When base class has a common function whose meaning depends on the actual derived class, we want to use before defining them –Must assign multiple meanings to the same function (polymorphism) –Powerful

Overriding: Virtual function definition changed in a derived class –We say it’s been "overidden" Similar to redefined –Recall: for standard functions So: - Virtual functions changed: overridden - Non-virtual functions changed: redefined Virtual Functions: Why Not All? Clear advantages to virtual functions as we’ve seen One major disadvantage: overhead! –Uses more storage –Late binding is "on the fly", so programs run slower So if virtual functions not needed, should not be used If a method is declared virtual in a class, –… it is automatically virtual in all derived classes It is a really, really good idea to make destructors virtual! virtual ~Shape(); –Reason: to invoke the correct destructor, no matter how object is accessed

Abstract and Concrete Classes Abstract Classes –Classes from which it is never intended to instantiate any objects Incomplete—derived classes must define the “missing pieces”. Too generic to define real objects. –Normally used as base classes and called abstract base classes Provide appropriate base class frameworks from which other classes can inherit. Concrete Classes –Classes used to instantiate objects –Must provide implementation for every member function they define Abstract Base Classes Pure virtual functions require no definition –Forces all derived classes to define "their own" version Class with one or more pure virtual functions is: abstract base class –Can only be used as base class –No objects can ever be created from it Since it doesn’t have complete "definitions" of all it’s members! If derived class fails to define all pure’s: It’s an abstract base class too

Abstract Classes and Pure virtual Functions Abstract base class can be used to declare pointers and references referring to objects of any derived concrete class Pointers and references used to manipulate derived-class objects polymorphically Polymorphism is particularly effective for implementing layered software systems – e.g., 1.Reading or writing data from and to devices. 2.Iterator classes to traverse all the objects in a container. Example – Graphical User Interfaces All objects on the screen are represented by derived classes from an abstract base class Common windowing functions Redraw or refresh Highlight Respond to mouse entry, mouse clicks, user actions, etc. Every object has its own implementation of these functions Invoked polymorphically by windowing system

#include using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout area() << '\n'; return 0; } OUTPUT: 20 10

Pure Virtual Functions A class is made abstract by declaring one or more of its virtual functions to be “pure” - i.e., by placing "= 0" in its declaration Base class might not have "meaningful” definition for some of its members! –Its purpose solely for others to derive from Recall class Figure –All figures are objects of derived classes Rectangles, circles, triangles, etc. –Class Figure has no idea how to draw! Make it a pure virtual function: virtual void draw() = 0; –"= 0" is known as a pure specifier. –Tells compiler that there is no implementation. Don’t need to know how to use it! - Principle of information hiding Virtual function table –Compiler creates it –Has pointers for each virtual member function –Points to location of correct code for that function Objects of such classes also have pointer –Points to virtual function table

Pure virtual Functions (continued) Every concrete derived class must override all base-class pure virtual functions –with concrete implementations If even one pure virtual function is not overridden, the derived-class will also be abstract –Compiler will refuse to create any objects of the class –Cannot call a constructor Purpose: When it does not make sense for base class to have an implementation of a function Software design requires all concrete derived classes to implement the function by Themselves Why Do we Want to do This? To define a common public interface for the various classes in a class hierarchy –Create framework for abstractions defined in our software system The heart of object-oriented programming Simplifies a lot of big software systems Enables code re-use in a major way Readable, maintainable, adaptable code

Relationships among objects in an inheritance hierarchy In public inheritance an object of a derived class can be treated as an object of its base class. Each derived class object is an object of its base class The is-a relationship applies only from a derived class to its direct and indirect base classes.

Invoking base-class functions from derived-class objects Three ways to aim base and derived class pointers at base and derived class objects. 1.Base class pointer at a base class object and invoke base class functionality 2.derived class pointer at a derived class object and invoke derived class functionality. Then we demonstrate the relationship between derived classes and base classes 3. base class pointer at a derived class object and showing that the base class functionality is indeed available in the derived class object

Cont… The relationship between derived classes and base classes (is-a relationship of inheritance ) by aiming a base class pointer at a derived class object and showing that the base class functionality is indeed available in the derived –class object. Creating objects and displaying their contents Aiming a base-class pointer at a base class object Aiming a derived class pointer at a derived class object Aiming a base class pointer at a derived class object

Aiming derived class pointers at base class objects Assign the address of a derived class object to a base class pointer because a derived class object is a base class object. The object points the pointer (ie. The base class object) The object does not provide a member function nor does it provide a data member to set I f the memory does not belong to the object, the member function might overwrite other important data in memory, possible data that belongs to a different object.

Cont… Example: If B is a base class and D is a derived class from b, then a pointer declared as a pointer to B can also be a pointer to D. B *cptr; //pointer to class B type variable B b; //base object D d; //derived object Cptr =&b; //cptr points to object b We can make cptr to point to the object d as follows: Cptr = &d; //cptr points to object d This is perfectly valid with C++ because d is an object derived from the class B.

Derived –class member –function call via base class pointers Derived class only members from a base class pointer that aimed at a derived class object if we explicitly cast the base class pointer to a derived class pointer – this is known as downcasting. Its possible to aim a base class pointer at a derived class object. A base class pointer can be used to invoke only the functions declared in the base class.

Virtual functions Virtual Function: A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function. selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. Pure Virtual Functions: It's possible to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class

Virtual functions Shape classes such as circle, triangle, rectangle and square are all derived from base class shape. Each of these classes might be endowed with the ability to draw itself via a member function draw, but the function for each shape is quite different. In a program that draws a set of shapes, it would be useful to be able to treat all the shapes generally as objects of the base class shape. Then, to draw any shape, we could simply use a base-class shape pointer to invoke function draw

Abstract classes The class as a type assume that programs will create objects of that type. To define classes from which the programmer never intends to instantiate any objects,such classes are called abstract classes. Normally these classes are used as base classes in inheritance hierarchies which is referred as abstract base classes. These classes cannot be used to instantiate objects, because the abstract classes are incomplete in which the derived classes must define the “missing pieces.”

Cont.. The purpose of an abstract class is to provide an appropriate base class from which other classes can inherit. Classes that can be used to instantiate objects are called concrete classes. Such classes provide implementations of every member function they define. The abstract class is to provide and appropriate base class from which other classes can inherit.

Cont… Classes that can be used to instantiate objects are called concrete classes. Such classes proved implementations of every member function they define. Example:1. abstract base class- two dimensional shape derive concrete classes- square, circle and triangle.

Cont… Example-2: Abstract base class: three dimensional shape Derive such classes: cube, sphere and cylinder. If someone tells you to “draw the two- dimensional shape,” what shape would you draw? Concrete classes provide the specifies that make it reasonable to instantiate objects.

Pure virtual function A class is made abstract by declaring one or more of its virtual functions to be “pure” A pure virtual function is specified by placing “=0” in its declaration, as in virtual void draw() const = 0; //pure virtual function The “=0” is known as a pure specifier.

Cont… Pure virtual functions do not provide implementations. Every concrete derived class must override all base-class pure virtual functions with concrete implementations of those functions. The difference between a virtual function and a pure virtual function is that a virtual function has an implementation and gives the derived class the option of overriding the function

Cont… A pure virtual function does not provide an implementation and requires the derived class to override the function (for that derived class to be concrete; otherwise the derived class remains abstract) Example: A company pays its employees weekly.

Cont… Types of four: 1. salaried employees are paid a fixed weekly regardless of the number of hours worked 2. Hourly employees are paid by the hour and receive overtime pay for all hours worked in excess of 40 hours 3. Commission employees are paid a percentage of their sales and base-salary-plus-commission employees receive a base salary plus a percentage of their sales. 4. For the current pay period, the company has decided to reward base-salary-plus-commission employees by adding 10 percent to their base salaries. Write a c++ program that performs its payroll calculations polymorphically.

Cont… example: employee S alaried employee Commission employee Hourly employee Basepluscommission employee

#include using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout area() << '\n'; return 0; } OUTPUT: 20 10

this Pointer: Special pointer this is used to access the pure virtual members of abstract base class. Example: In abstract base class Polygon the special pointer this is used to access the pure virtual members, even though Polygon itself has no implementation for this function: #include // pure virtual members can be called // from the abstract base class using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area() =0; void printarea() { cout area() << '\n'; } }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly1->printarea(); ppoly2->printarea(); return 0; } OUTPUT: 20 10