K. Stirewalt CSE 335: Software Design Foundations: Language Mechanisms and Primitive OO Concepts Lecture 2: Polymorphism Topics: – Polymorphism and virtual.

Slides:



Advertisements
Similar presentations
Polymorphism and Virtual Functions. Topics Polymorphism Virtual Functions Pure Virtual Functions Abstract Base Classes Virtual Destructors V-Tables Run.
Advertisements

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Dynamic Memory Management CAS CS210 Ying Ye Boston University.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
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.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
. Virtual Classes & Polymorphism. Example (revisited) u We want to implement a graphics system u We plan to have lists of shape. Each shape should be.
Polymorphism, Virtual Methods and Abstract Classes.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation - a language mechanism for restricting access to some.
DERIVED CLASSES AND INHERITANCE Moshe Fresko Bar-Ilan University Object Oriented Programing
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
12/08/08MET CS Fall Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
C++ facts From What all is inherited from parent class in C++? Following are the things which a derived class inherits from its.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
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.
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.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
Inheritence Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September.
Polymorphism and Virtual Functions. Topics Polymorphism Virtual Functions Pure Virtual Functions Abstract Base Classes Virtual Destructors V-Tables Run.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Foundations: Language mechanisms and primitive OO concepts Lecture 1: Classification and Inheritance Michigan State University Spring 2008 E. Kraemer Notes.
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
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
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.
1 Inheritance and Polymorphism Chapter Getting Started Continue the Cat Management example from previous presentation.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
CPSC 252Inheritance II Page 1 Inheritance & Pointers Consider the following client code: const int MAXCLOCKS = 2; Clock* clockPtr[ MAXCLOCKS ]; clockPtr[0]
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.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CMSC 202 Polymorphism.
Templates.
7. Inheritance and Polymorphism
Inheritance and Big O And your first reading assignment
Class A { public : Int x; A()
Polymorphism.
Inheritance and Run time Polymorphism
Review: Two Programming Paradigms
Inheritance, Polymorphism and the Object Memory Model
Polymorphism CT1513.
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Inheritance, Polymorphism and the Object Memory Model
Lecture 6: Polymorphism
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:

K. Stirewalt CSE 335: Software Design Foundations: Language Mechanisms and Primitive OO Concepts Lecture 2: Polymorphism Topics: – Polymorphism and virtual functions in C++ – Simple uses of polymorphism – Implementation of virtual and non-virtual functions – Common mistakes and need for virtual destructors

K. Stirewalt CSE 335: Software Design Pop quiz void generateReport( Employee& empl ) {... empl.print(cout);... } int main(void) { Employee doe( “ John ”, “ Doe ”, 235); Manager howell( “ Charles ”, “ Howell ”, 235, 3); generateReport(howell); } Question: Which method invoked to carry out this operation when empl is actually an instance of Manager?

K. Stirewalt CSE 335: Software Design Motivation We should be able to develop clients that request an object to perform some operation and leave it to the object to choose the method This capability, called polymorphism, is one of the defining characteristics of OO In C++, we implement polymorphic operations by declaring member functions to be virtual

K. Stirewalt CSE 335: Software Design Example: declaring virtual function class Employee { private: string first_name, last_name; short department; public: virtual void print( ostream& ) const; }; class Manager : public Employee { private: list group; short level; public: void print( ostream& ) const; }; Observe: function member declared virtual in base class. Observe: no need to “redeclare” print as virtual.

K. Stirewalt CSE 335: Software Design Example: Virtual functions int main(void) { Employee doe( “ John ”, “ Doe ”, 235); Manager howell( “ Charles ”, “ Howell ”, 235, 3); doe.print(cout); // invokes Employee::print() howell.print(cout); // invokes Manager::print() Employee* ePtr = &howell; ePtr->print(cout); // invokes Manager::print() }

K. Stirewalt CSE 335: Software Design Virtual-function definitions void Employee::print( ostream& os ) const { os << “ Name: ” << first_name << “ “ << last_name << endl << “ Dept: “ << department; } void Manager::print( ostream& os ) const { Employee::print(os); os << “ Level: “ << level; } Question: What happens here???

K. Stirewalt CSE 335: Software Design Exercise We want to store different geometric objects in a list and compute their area. Develop a class hierarchy with classes Shape, Circle, and Rectangle. The following code should compile correctly: list myShapes; Circle* circ = new Circle(10); Rectangle* rect = new Rectangle(20, 40); myShapes.push_back(circ); myShapes.push_back(rect); for (list ::iterator it = myShapes.begin(); it != myShapes.end(); it++) cout area() << endl;

K. Stirewalt CSE 335: Software Design Heterogeneous containers Inheritance + polymorphism can be used to implement containers that can hold different types of elements –Declare base class from which all element classes derive Base class declares a polymorphic operation –In C++, developer of base class declares a virtual member function Each element class may provide its own method for the operation –Instantiate container with type “pointer to base class” –Clients, invoke operations on elements taken from container without knowing actual type of the elements!

K. Stirewalt CSE 335: Software Design > Henceforth, we will use polymorphism frequently and in combination with other language features to build reliable and reusable software structures Because it is so central, it is important that you REALLY understand how it works My theory: No better way than to look at how it is implemented!

K. Stirewalt CSE 335: Software Design Question Thinking in terms of system-level resources, what is the mechanism by which virtual functions are actually implemented? Answer: Each instance of a class that declares or inherits virtual member functions carries with it a pointer to a table (called a vtable) of pointers to member functions –When a virtual member function is invoked, a pointer to the function to be dispatched is found by looking it up in the vtable. –Instances of different classes point to different vtables. –Owing to this indirection, a client may invoke the method appropriate to the class used to originally instantiate the object without knowing that class!

K. Stirewalt CSE 335: Software Design Recall: Conceptual model of memory use by a running process Process partitioned into 2 major chunks: –static part contains program code +... static data, vtables, etc –dynamic part contains run-time stack + heap all local variables and objects created using new live here Run-time stack Heap Program code + static data

K. Stirewalt CSE 335: Software Design Consider the following source code class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … void vf1(…) {…} void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } Note: No virtual member functions yet; we’ll bring those in later.

K. Stirewalt CSE 335: Software Design Code compiled and linked... class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … void vf1(…) {…} void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … main() {…} a.out Compilation/linking

K. Stirewalt CSE 335: Software Design Program is executed... class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … void vf1(…) {…} void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … main() {…}

K. Stirewalt CSE 335: Software Design Program is executed... class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … void vf1(…) {…} void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … main() {…} Process begins executing in function main

K. Stirewalt CSE 335: Software Design Object myC1 constructed... class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … void vf1(…) {…} void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … main() {…} myC1 attr1 attr2

K. Stirewalt CSE 335: Software Design Object myC2 constructed class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … void vf1(…) {…} void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … main() {…} myC1 myC attr1 attr2 attr1 attr2

K. Stirewalt CSE 335: Software Design vf2() invoked on myC2 class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … void vf1(…) {…} void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … main() {…} myC1 myC2 attr1 attr2 attr1 attr2 C::vf2 activation this …

K. Stirewalt CSE 335: Software Design Now let’s bring in the virtuals!

K. Stirewalt CSE 335: Software Design Consider these modifications to our source code class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } Note: Only change to source is introduction of the 2 virtual keywords

K. Stirewalt CSE 335: Software Design main() {…} Compiling and linking… class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … Class C vtable a.out Note: Existence of virtual functions in class C caused the compiler to create a static object called the class C vtable.

K. Stirewalt CSE 335: Software Design main() {…} Program is executed class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … Class C vtable

K. Stirewalt CSE 335: Software Design main() {…} Object myC1 created... class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … myC1 Class C vtable attr1 attr2 vptr

K. Stirewalt CSE 335: Software Design main() {…} Object myC1 created... class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … myC1 Class C vtable attr1 attr2 vptr Note: “extra” field in myC1

K. Stirewalt CSE 335: Software Design main() {…} Creating myC2 class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … myC1 myC Class C vtable attr1 attr2 vptr attr1 attr2 vptr

K. Stirewalt CSE 335: Software Design main() {…} Creating myC2 class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … myC1 myC Class C vtable attr1 attr2 vptr attr1 attr2 vptr Note: “extra” field in myC2

K. Stirewalt CSE 335: Software Design main() {…} Dynamic dispatch of vf2 [step 1] class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … myC1 myC Class C vtable attr1 attr2 vptr attr1 attr2 vptr

K. Stirewalt CSE 335: Software Design main() {…} Dynamic dispatch of vf2 [step 2] class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … myC1 myC Class C vtable attr1 attr2 vptr attr1 attr2 vptr

K. Stirewalt CSE 335: Software Design main() {…} Dynamic dispatch of vf2 [step 3] class C { protected: unsigned attr1; float attr2; … public: void f1(…){ … } … virtual void vf1(…) {…} virtual void vf2(…) {…} }; int main(void) { C myC1(8,32.0); C myC2(16, -64.5); myC2.vf2(); } C::f1(…){…} … C::vf1(…){…} C::vf2(…){…} … myC1 myC Class C vtable attr1 attr2 vptr attr1 attr2 vptr C::vf2 activation...

K. Stirewalt CSE 335: Software Design More interesting example class D : public C { protected: unsigned attr3; … public: void f1(…); … void vf1(…); void vf2(…); virtual void vf3(…); }; int main(void) { C myC1(8,32.0); D myD1(16, -64.5, 38); myD1.vf2() }

K. Stirewalt CSE 335: Software Design More interesting example class D : public C { protected: unsigned attr3; … public: void f1(…); … void vf1(…); void vf2(…); virtual void vf3(…); }; int main(void) { C myC1(8,32.0); D myD1(16, -64.5, 38); myD1.vf2() } Question: How would the process memory map look in this example?

K. Stirewalt CSE 335: Software Design More interesting example C::f1(…) class D : public C { protected: unsigned attr3; … public: void f1(…); … void vf1(…); void vf2(…); virtual void vf3(…); }; int main(void) { C myC1(8,32.0); D myD1(16, -64.5, 38); myD1.vf2(); } D::vf2(…) C::vf1(…) C::vf2(…) Class C vtable myC myD1 D::vf3(…) vptr attr1 attr2 vptr attr1 attr2 38 attr3 Class D vtable D::vf1(…) D::f1(…) main(…)

K. Stirewalt CSE 335: Software Design Exercise void myPrint( Employee e ) { e.print(cout); } int main(void) { Manager howell( … ); myPrint(howell); } Question: Which print method invoked when actual parameter is Manager? Observe: Actual parameter is a value, not a reference.

K. Stirewalt CSE 335: Software Design Question A compiler translates a program in one language into an equivalent program in another language, which is “closer to the machine”. How would the compiler-generated code for function myPrint differ when Employee::print is virtual vs. non-virtual?

K. Stirewalt CSE 335: Software Design Code for myPrint (print NOT virtual) pushl%ebp movl%esp, %ebp movl8(%ebp), %eax pushl$_cout pushl%eax call_print__8EmployeeR7ostream movl%ebp, %esp popl%ebp ret

K. Stirewalt CSE 335: Software Design Code for myPrint (print virtual) pushl%ebp movl%esp, %ebp movl8(%ebp), %edx pushl$_cout pushl%edx movl4(%edx), %ecx; put vptr in ecx movl12(%ecx), %eax; put address at offset ; 12 in vtable into eax call*%eax; call function pointed to ; by eax movl%ebp, %esp popl%ebp ret

K. Stirewalt CSE 335: Software Design Observations Lots of things happen when we define an member function to be virtual –Better left to the compiler –No significant inefficiency (one extra indirection per virtual function invocation)

K. Stirewalt CSE 335: Software Design Destructors in derived classes class Target { public: Target() { numtargets++; } ~Target() { --numtargets; } static int numberOfTargets() { return numtargets; } private: static int numtargets; }; class Tank : public Target { public: Tank( const string& tId ) : tankId(tId) { numtanks++; } ~Tank() { numtanks--; } static int numberOfTanks() { return numtanks; } private: static int numtanks; const string tankID; };

K. Stirewalt CSE 335: Software Design Exercise Target* target = new Tank(“T-19”);. delete target; What happens here? (Think about what destructors are called) Notice: base and derived classes

K. Stirewalt CSE 335: Software Design Virtual Destructor class Target { public: Target() { numtargets++; } virtual ~Target () { --numtargets; } static int numberOfTargets() { return numtargets; } private: static int numtargets; }; Solution: Make destructor virtual.