Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Inheritance and Polymorphism.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 15: Polymorphism,
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 17 – Payroll Application: Introducing Inheritance.
Inheritance, Polymorphism, and Virtual Functions.
Inheritance, Polymorphism, and Virtual Functions
Inheritance Chapter 11.
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.
Chapter 12: Adding Functionality to Your Classes.
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.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
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.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using work from: Starting Out with C++ Early Objects Eighth Edition.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
11-1 Chapter.9 Classes & Objects: Inheritance –What Is Inheritance? –Calling the Superclass Constructor –Overriding Superclass Methods –Protected Members.
AN INTRODUCTION TO INHERITANCE. In your group Define 5 attributes that you would use to describe persons. Define 3 different attributes that can describe.
Chapter Topics Chapter 10 discusses the following main topics:
Inheriatance. 9-2 What is Inheritance? Generalization vs. Specialization Real-life objects are typically specialized versions of other more general objects.
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.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
More on Inheritance Chapter 11 Continued. Reminders Overloading – different signatures Overriding – same signatures Preventing overriding – use final.
11-2  What Is Inheritance?  Calling the Superclass Constructor  Overriding Superclass Methods  Protected Members  Chains of Inheritance  The Object.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
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.
Chapter -6 Polymorphism
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley What Is Inheritance? 15.1.
© 2010 Pearson Addison-Wesley. All rights reserved. AN INTRODUCTION TO INHERITANCE.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 8 1.
1 CSE 2341 Object Oriented Programming with C++ Note Set #12.
A First Book of C++ Chapter 12 Extending Your Classes.
Chapter 11 Inheritance. Contents I.What Is Inheritance? II. Calling the Superclass Constructor III. Overriding Superclass Methods IV. Protected Members.
Inheritance and Polymorphism
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CMSC 202 Polymorphism.
Polymorphism, Abstract Classes & Interfaces
Object-Oriented Programming
Inheritance, Polymorphism, and Virtual Functions
Inheritance & Polymorphism
by Tony Gaddis and Godfrey Muganda
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
An introduction to inheritance
Starting Out with Java: From Control Structures through Objects
Inheritance Using work from:
Learning Objectives Inheritance Virtual Function.
Inheritance, Polymorphism, and Virtual Functions
Polymorphism, Abstract Classes & Interfaces
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
C++ Inheritance.
Chapter 11: Inheritance Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Programming in C# CHAPTER 5 & 6
Computer Science II for Majors
Presentation transcript:

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Copyright © 2012 Pearson Education, Inc What Is Inheritance?

Copyright © 2012 Pearson Education, Inc. What Is Inheritance? Provides a way to create a new class from an existing class The new class is a specialized version of the existing class

Copyright © 2012 Pearson Education, Inc. Example: Insects

Copyright © 2012 Pearson Education, Inc. The "is a" Relationship Inheritance establishes an "is a" relationship between classes: –A poodle is a dog –A car is a vehicle –A flower is a plant –A football player is a athlete

Copyright © 2012 Pearson Education, Inc. Inheritance – Terminology and Notation Base class parentsuperclass Derived class childsubclass Notation: class Student // base class {... }; class UnderGrad : public student // derived class {... }; "inherits from" uses public inheritance class access specifier

Copyright © 2012 Pearson Education, Inc. Graded Activity Version 1  pr 15-1  pr15-2

Copyright © 2012 Pearson Education, Inc. Back to the ‘is a’ Relationship An object of a derived class 'is a' object of the base class Example: –an UnderGrad is a Student –a Mammal is a Animal A derived object has all of the characteristics of the base class

Copyright © 2012 Pearson Education, Inc. What Does a Child Have?  An object of the derived class has:  all members defined in the child class  all members declared in the parent class  An object of the derived class can use:  all public members defined in the child class  all public members defined in the parent class  Note: derived classes do not inherit:  base class constructors or destructors  overloaded operators

Copyright © 2012 Pearson Education, Inc Protected Members and Class Access

Copyright © 2012 Pearson Education, Inc. Protected Members and Class Access protected –member access specification: like private, but accessible by objects of derived class Class access specifier –determines how private, protected, and public members of base class are inherited by the derived class

Copyright © 2012 Pearson Education, Inc. Class Access Specifiers public An object of a derived class can be treated as an object of the base class (not vice-versa) protected More restrictive than public, but it allows derived classes to know the details of the parents private Prevents objects of derived class from being treated as objects of base class.

Copyright © 2012 Pearson Education, Inc. Graded Activity Version 2  pr 15-3

Copyright © 2012 Pearson Education, Inc. Inheritance vs. Access private: x protected: y public: z private: x protected: y public: z private: x protected: y public: z Base class members x is inaccessible private: y private: z x is inaccessible protected: y protected: z x is inaccessible protected: y public: z How inherited base class members appear in a derived class : private base class : protected base class : public base class class UnderGrad : public student

Copyright © 2012 Pearson Education, Inc. More Inheritance vs. Access private members: char letter; double score; void calcGrade(); public members: void setScore(double); double getScore(); char getLetter(); class Grade private members: int numQuestions; double pointsEach; int numMissed; public members: Test(int, int); class Test : public Grade When Test class inherits from Grade class using public class access, it looks like this: private members: int numQuestions: double pointsEach; int numMissed; public members: Test(int, int); void setScore(double); double getScore(); double getLetter(); Only member data (fields) are stored in an object. One copy of the executable code for the functions (methods) is shared by all of the objects. char letter; double score; void calcGrade();

Copyright © 2012 Pearson Education, Inc. More Inheritance vs. Access (2) private members: char letter; double score; void calcGrade(); public members: void setScore(double); double getScore(); char getLetter(); class Grade private members: int numQuestions; double pointsEach; int numMissed; public members: Test(int, int); class Test : protected Grade When Test class inherits from Grade class using protected class access, it looks like this: private members: int numQuestions: double pointsEach; int numMissed; protected members: void setScore(double); double getScore(); double getLetter(); public members: Test(int, int); char letter; double score; void calcGrade();

Copyright © 2012 Pearson Education, Inc. More Inheritance vs. Access (3) private members: char letter; double score; void calcGrade(); public members: void setScore(double); double getScore(); char getLetter(); class Grade private members: int numQuestions; double pointsEach; int numMissed; public members: Test(int, int); class Test : private Grade When Test class inherits from Grade class using private class access, it looks like this: private members: int numQuestions: double pointsEach; int numMissed; void setScore(double); double getScore(); double getLetter(); public members: Test(int, int); char letter; double score; void calcGrade();

Copyright © 2012 Pearson Education, Inc. More Inheritance vs. Access (2) (original version) private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); When Test class inherits from Grade class using protected class access, it looks like this: private members: int numQuestions: float pointsEach; int numMissed; public members: Test(int, int); protected members: void setScore(float); float getScore(); float getLetter(); class Test : protected Grade

Copyright © 2012 Pearson Education, Inc. More Inheritance vs. Access (3) (original version) private members: int numQuestions: float pointsEach; int numMissed; void setScore(float); float getScore(); float getLetter(); public members: Test(int, int); private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); When Test class inherits from Grade class using private class access, it looks like this: class Test : private Grade

Copyright © 2012 Pearson Education, Inc Constructors and Destructors in Base and Derived Classes

Copyright © 2012 Pearson Education, Inc. Constructors and Destructors in Base and Derived Classes Derived classes can have their own constructors and destructors When an object of a derived class is created: –the base class’s constructor is executed first, followed by the derived class’s constructor When an object of a derived class is destroyed: –its destructor is called first, then that of the base class

Copyright © 2012 Pearson Education, Inc. Constructors and Destructors in Base and Derived Classes

Copyright © 2012 Pearson Education, Inc.

Program 5-14 (Continued)

Copyright © 2012 Pearson Education, Inc. Base Class / Derived Class  pr 15-4

Copyright © 2012 Pearson Education, Inc. Rectangle / Cube Classes  pr 15-5

Copyright © 2012 Pearson Education, Inc. Automobile, Car, Truck, SUV Classes  pr 15-6

Copyright © 2012 Pearson Education, Inc. Passing Arguments to Base Class Constructor Allows selection between multiple base class constructors (overloaded constructors) Specify arguments for the base constructor (superclass) in the derived constructor heading: Square::Square(int side) : Rectangle(side, side) Can also be done with inline constructors Must be done if base class has no default constructor Square inherits from Rectangle

Copyright © 2012 Pearson Education, Inc. Passing Arguments to Base Class Constructor Square::Square(int side) : Rectangle(side,side) derived class constructorbase class constructor derived constructor parameter base constructor arguments

Copyright © 2012 Pearson Education, Inc Redefining Base Class Functions

Copyright © 2012 Pearson Education, Inc. Redefining Base Class Functions Redefined function: –A function in a derived class that has the same name and parameter list as a function in the base class Typically used to change the functionality of an inherited function

Copyright © 2012 Pearson Education, Inc. Redefining Base Class Functions Not the same as overloading: –with overloading, the parameter lists must be different Objects of the base class use the base class version of function Objects of the derived class use the derived class version of function

Copyright © 2012 Pearson Education, Inc. Base Class Note setScore function

Copyright © 2012 Pearson Education, Inc. Derived Class Modifies SetScore Function Redefined setScore function

Copyright © 2012 Pearson Education, Inc. From Program 15-7

Copyright © 2012 Pearson Education, Inc. CurvedActivity Class  pr 15-7

Copyright © 2012 Pearson Education, Inc. Problem with Redefining Consider this situation: –Class BaseClass defines functions x() and y(). x() calls y() –Class DerivedClass inherits from BaseClass and redefines function y() –An object D of class DerivedClass is created and function x() is called. –When x() is called, which y() is used, the one defined in BaseClass or the the redefined one in DerivedClass?

Copyright © 2012 Pearson Education, Inc. Problem with Redefining BaseClass DerivedClass void X(); void Y(); void X();// unmodified void Y();// refedined DerivedClass D; D.X(); Object D invokes function X() In BaseClass. function X() invokes function Y() in BaseClass, not function Y() in DerivedClass This is because function calls are bound at compile time. This is static binding.

Copyright © 2012 Pearson Education, Inc. BaseClass / DerivedClass Classes  pr 15-8

Copyright © 2012 Pearson Education, Inc Class Hierarchies

Copyright © 2012 Pearson Education, Inc. Class Hierarchies A base class can be derived from another base class.

Copyright © 2012 Pearson Education, Inc. PassFailActivity, PassFailExam  pr 15-9

Copyright © 2012 Pearson Education, Inc. Class Hierarchies Consider the GradedActivity, FinalExam, PassFailActivity, PassFailExam hierarchy in Chapter 15.

Copyright © 2012 Pearson Education, Inc Polymorphism and Virtual Member Functions

Copyright © 2012 Pearson Education, Inc. Polymorphism and Virtual Member Functions Virtual member function –function in base class that expects to be redefined in derived class Function defined with key word virtual : virtual void Y() {...} Supports dynamic binding: –functions bound at run time to the function that they call Without virtual member functions, C++ uses static (compile time) binding

Copyright © 2012 Pearson Education, Inc. Consider this function (from Program 15-9) Because the parameter in the displayGrade function is a GradedActivity reference variable, it can reference any object that is derived from GradedActivity. That means we can pass a GradedActivity object, a FinalExam object, a PassFailExam object, or any other object that is derived from GradedActivity. A problem occurs in Program however...

Copyright © 2012 Pearson Education, Inc

Copyright © 2012 Pearson Education, Inc. As you can see from the example output, the getLetterGrade member function returned ‘C’ instead of ‘P’. This is because the GradedActivity class’s getLetterGrade function was executed instead of the PassFailActivity class’s version of the function.

Copyright © 2012 Pearson Education, Inc. Static Binding Program displays 'C' instead of 'P' because the call to the getLetterGrade function is statically bound (at compile time) with the GradedActivity class's version of the function. We can remedy this by making the function virtual.

Copyright © 2012 Pearson Education, Inc. Virtual Functions A virtual function is dynamically bound to calls at runtime. At runtime, C++ determines the type of object making the call, and binds the function to the appropriate version of the function.

Copyright © 2012 Pearson Education, Inc. PassFailActivity  pr  GradedActivity &  virtual keyword not used

Copyright © 2012 Pearson Education, Inc. Virtual Functions To make a function virtual, place the virtual key word before the return type in the base class's declaration: virtual char getLetterGrade() const; The compiler will not bind the function to calls. Instead, the program will bind them at runtime.

Copyright © 2012 Pearson Education, Inc. GradedActivity version 3  pr  void displayGrade(const GradedActivity &);  virtual char getLetterGrade() const declared in GradedActivity.h  function declared virtual in derived class PassFailActivity (not required)

Copyright © 2012 Pearson Education, Inc. Updated Version of GradedActivity The function is now virtual. The function also becomes virtual in all derived classes automatically!

Copyright © 2012 Pearson Education, Inc. If we recompile our program with the updated versions of the classes, we will get the right output, shown here: (See Program in the book.) This type of behavior is known as polymorphism. The term polymorphism means the ability to take many forms. Program demonstrates polymorphism by passing objects of the GradedActivity and PassFailExam classes to the displayGrade function.

Copyright © 2012 Pearson Education, Inc.

Polymorphism Requires References or Pointers Polymorphic behavior is only possible when an object is referenced by a reference variable or a pointer, as demonstrated in the displayGrade function.

Copyright © 2012 Pearson Education, Inc. GradedActivity / PassFailExam  pr  GradedActivity object  PassFailExam object  virtual char getLetterGrade() const  void displayGrade(const GradedActivity &)

Copyright © 2012 Pearson Education, Inc. Base Class Pointers Can define a pointer to a base class object Can assign it the address of a derived class object

Copyright © 2012 Pearson Education, Inc. Base Class Pointers Base class pointers and references only know about members of the base class –So, you can’t use a base class pointer to call a derived class function Redefined functions in a derived class will be ignored unless the base class declares the function virtual

Copyright © 2012 Pearson Education, Inc. PassFailExam / GradedActivity  pr  GradedActivity *  polymorphic behavior

Copyright © 2012 Pearson Education, Inc. PassFailActivity / PassFailExam  pr  base class pointer to a derived class object  array of objects of type GradedActivity

Copyright © 2012 Pearson Education, Inc. Redefining vs. Overriding In C++, redefined functions are statically bound and overridden functions are dynamically bound. So, a virtual function is overridden, and a non- virtual function is redefined.

Copyright © 2012 Pearson Education, Inc. Virtual Destructors It's a good idea to make destructors virtual if the class could ever become a base class. Otherwise, the compiler will perform static binding on the destructor if the class ever is derived from. See Program for an example

Copyright © 2012 Pearson Education, Inc. Animal / Dog Classes  pr  overrides (redefines a virtual base class function)  pr  virtual destructor

Copyright © 2012 Pearson Education, Inc Abstract Base Classes and Pure Virtual Functions

Copyright © 2012 Pearson Education, Inc. Abstract Base Classes and Pure Virtual Functions Pure virtual function: –a virtual member function that must be overridden in a derived class that has objects An abstract base class contains at least one pure virtual function: virtual void Y() = 0; The = 0 indicates a pure virtual function There can be no function definition in the base class

Copyright © 2012 Pearson Education, Inc. Abstract Base Classes and Pure Virtual Functions Abstract base class: –class cannot be used to create objects! –Serves as a basis for derived classes that may/will have objects A class becomes an abstract base class when one or more of its member functions is a pure virtual function

Copyright © 2012 Pearson Education, Inc. CsStudent Class  pr  abstract class  pure virtual function

Copyright © 2012 Pearson Education, Inc Multiple Inheritance

Copyright © 2012 Pearson Education, Inc. Multiple Inheritance A derived class can have more than one base class Each base class can have its own access specification in derived class's definition: class cube : public square, public rectSolid; class square class rectSolid class cube

Copyright © 2012 Pearson Education, Inc. Multiple Inheritance Arguments can be passed to both base classes' constructors: cube::cube(int side) : square(side), rectSolid(side, side, side); Base class constructors are called in the order given in class declaration, not in order used in class constructor

Copyright © 2012 Pearson Education, Inc. Multiple Inheritance Problem: what if base classes have member variables/functions with the same name? Solutions: –Derived class redefines the multiply-defined function –Derived class invokes a member function in a particular base class using the scope resolution operator :: Compiler errors occur if a derived class uses a multiple inheritance base class function without one of these solutions

Copyright © 2012 Pearson Education, Inc. Date, Time, DateTime Classes  pr  multiple inheritance