Presentation is loading. Please wait.

Presentation is loading. Please wait.

12/08/08MET CS 563 - Fall 2008 10. Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as.

Similar presentations


Presentation on theme: "12/08/08MET CS 563 - Fall 2008 10. Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as."— Presentation transcript:

1 12/08/08MET CS 563 - Fall 2008 10. Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as derived, of some (any given) hierarchy; will adjust appropriately for the corresponding derived classes. Such functions are called virtual functions generic programming a programming approach whose goal it is to create programs that are independent of the specific types basis of

2 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Virtual Functions – Basic Implementation Idea Declare a function as virtual as high in the hierarchy as necessary in order to make it available to all objects of this class and its derived classes Use the override mechanism to adjust the function appropriately in the derived classes. Thus the virtual function takes many (Greek: poly) different forms (Greek: morph) depending on the actual argument type Polymorphism Advantage: easy code reuse and modification: derived class inherits from base (as in regular inheritance) and more flexibility as all object types can access method (see examples of base pointers pointing to derived class objects)

3 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Virtual Function Alternatives: switch Logic Question: Question: Are there other mechanism to instatiate different procedures depending on the type of the actual argument? Yes. The same functionality can be be implemented by switch logic Example: Example: Given base class Shape derived classes Circle, Rectangle function draw() differs for Circle and Rectangle Without introducing virtual functions, the appropriate function can be chosen using switch logic as follows: switch (type): { case Circle: drawCircle(); break; case Rectangle: drawRectangle (); break; default: cout<<”Invalid Type”<<endl; }

4 12/08/08MET CS 563 - Fall 2008 10. Polymorphism switch Logic- Pros and Cons Pros: easy first implementation with familiar syntax constructs; no learning effort/time.Cons: adding new type requires changing all occurrences of switch statements in the program; all possible types must be taken into account in switch statement;

5 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Virtual Function Definition As any other member function, but preceded by the keyword virtual function prototype in class: class { … virtual … }; function definition typically outside class: :: Example: Shape Interface : draw();// virtual … Rectangle Interface: draw(); // virtual … Circle Interface: draw(); // virtual … is-a

6 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Virtual Function Example class Shape{ … virtual void draw() const; // prototype of virtual function draw() in // base class Shape …. }; void Shape :: draw() const //definition of draw() of base class Shape { } class Circle : public Shape{ … virtual void draw() const; // prototype of virtual function draw() in // derived class Circle …. }; void Circle :: draw() const //definition of draw() of derived class Circle { } //Similarly for derived class Rectangle

7 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Dynamic and Static Binding Assume: Assume: some object of a derived class type is declared, e.g. Circle round; Exactly what function will be used for the call in main() round.draw(); is resolved at compile time and round will always be bound to a method of class Circle. In other words the binding for round as shown above cannot be changed during run time and is therefore called static binding. Problem: Problem: Is it possible to resolve the binding at run time, and have the ability to use different functions with the same object as needed? A mechanism that makes the binding decision at run time is called dynamic binding. Dynamic Binding in C++: declare base class pointer assign pointer to point to a derived class object call virtual function with base class pointer: the function of the class of the object the pointer points to will be invoked and this decision is made at run time

8 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Dynamic and Static Binding - Example Shape * sPtr; // sPtr is pointer to base class Shape, Shape s;// is object of base class Shape Circle c ;// c is object of derived class Circle Rectangle r ; // r is object of derived class Rectangle sPtr = &s;// assignment performed at run-time sPtr -> draw();// draw() of base class Shape called; // decision made at run-time sPtr = &c; // assignment performed at run-time sPtr -> draw();// draw() of derived class Circle called; // decision made at run-time sPtr = &r; // assignment performed at run-time sPtr -> draw();// draw() of derived class Rectangle called; // decision made at run-time c.draw();// draw() of derived class Circle called; // decision made at compile-time // c is declared as Circle; this is known at compile time and // cannot change during program execution dynamic binding static binding same call, different functions executed

9 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Virtual Function - Notes How is the concept of the virtual base function different from any other base function that is anyway overridden in the derived class if needed? How is the concept of the virtual base function different from any other base function that is anyway overridden in the derived class if needed? If the function is not declared as virtual, a base class pointer invokes the base class method, even if the pointer points to a derived class object and the dynamic binding mechanism as described in the previous slide does not work. Can we call a base class virtual function through a base class pointer pointing to a derived class object? Yes, provided we explicitly specify it is the base class function we want: Shape*sPtr; Circle c; sPtr = &c; sPtr -> draw(); // draw() of derived class Circle is called sPtr ->Shape :: draw(); // draw() of base class Shape is called

10 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Virtual Function – Notes (continued) Once declared a virtual function, the function remains virtual for all derived classes of the hierarchy, i.e. strictly speaking we do not need to repeat the virtual keyword in the derived classes, as it exists implicitly. However it greatly helps the clarity of the program to include virtual in every derived class. A derived class may or may not include a virtual base class function in its definition. In the latter case the virtual function is simply inherited, as any other member function.

11 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Virtual Function – Destructors Problem: Problem: Assume a base class pointer is pointing to a derived class object, e.g. for the purposes of dynamic binding. Trying to destroy this derived class object by applying delete on the base class pointer will result in a call to the base class destructor and may not take care of data specific to the derived class such as arrays defined in the derived class. Solution: Solution: Declare a virtual base-class destructor. All derived class destructors become virtual and automatically override the virtual base- class destructor. If delete is applied to a base class pointer the destructor for the object the pointer points to is called. The base class destructor is always called after the derived class destructor, so all data of the derived and base class will be taken care of.

12 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Abstract and Concrete Classes – Goal Goal: Goal: Introduce higher level classes that capture the general properties and functions of a multiple class hierarchy, i.e. provide the rudimentary interface/implementation to be inherited by derived classes; support the building of taxonomies through e.g. is-a relationship with lower level classes provide a base class to define pointer variables for dynamic binding, but are not used for instantiation of objects; Example: FurnitureChair Abstract Class: has no objects, i.e. no objects of abstract class can be defined; is typically a base class. Concrete Class: has object instances; typically a derived class. Defining a furniture object is problematic and not very useful Defining a chair object is natural and useful is-a

13 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Abstract and Concrete Classes – Definition Definition: Definition: No new special class is introduced!! Instead Introduce a new type of virtual functions that has no definition in the class it is defined and thus cannot be invoked with objects of the class. Such functions are called pure virtual functions and are declared by adding "= 0" at the end of the function prototype: class { … virtual = 0; // pure virtual }; Define a class as abstract if and only if it has at least one pure virtual function, e.g. has now become an abstract class. Override the pure virtual function by eventually supplying a definition in one of the derived classes. Note: Note: Abstract classes need not be part of every program, but they help structure the program and most larger applications make use of them. Typically the higher levels of the class hierarchy are abstract classes.

14 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Abstract and Concrete Classes – Example ( Abstract and Concrete Classes – Example (D&D Figure 10.1) Employee Interface : earnings();// pure virtual … Data: firstName lastName abstract class concrete class Boss Interface : earnings();// virtual … Data : weeklySalary CommissionWorker Interface : earnings();// virtual … Data : salry commission quantity PieceWorker Interface : earnings();// virtual … Data: wagePerPiece quantity …

15 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Example – Abstract Base Class class Employee { public: // conversion constructor: strings/char-arrays to Employee; // constructs deep copy of arguments Employee( const char *, const char * ); ~Employee(); // destructor reclaims memory const char *getFirstName() const; const char *getLastName() const; // Pure virtual function makes Employee abstract base class virtual double earnings() const = 0; // pure virtual, no definition, // no invocation virtual void print() const; // virtual, definition for base class private: char *firstName; char *lastName; };

16 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Example – Concrete Derived Class class Boss : public Employee { public: Boss( const char *, const char *, double = 0.0 ); //Constuctor //default for weeklySalary is 0 void setWeeklySalary( double ); //new method virtual double earnings() const; //definition provided virtual void print() const; // definition of base class specialized private: double weeklySalary; //new private data member };

17 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Example – Constructors Employee::Employee( const char *first, const char *last ) { firstName = new char[ strlen( first ) + 1 ]; //test whether space was really allocated with assert(), see DD,p.446 //assert(condition) is defined in assert.h and tests its argument //if condition is false (0) abort of stdlib.h is called and program terminated assert( firstName != 0 ); // test that new worked strcpy( firstName, first ); lastName = new char[ strlen( last ) + 1 ]; assert( lastName != 0 ); strcpy( lastName, last ); } Boss::Boss( const char *first, const char *last, double s ) : Employee( first, last ) // call base-class constructor { setWeeklySalary( s ); } tests value of argument, if false program interrupted and error message with the corresponding line printed; needs assert.h

18 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Example – base and derived class method definition earnings() pure virtual in Employee // Get the Boss's pay double Boss::earnings() const { return weeklySalary; } // Print the name of the Employee void Employee::print() const{ cout << firstName << ' ' << lastName; } // Print the Boss's name void Boss::print() const{ cout << "\n Boss: "; Employee::print(); }

19 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Polymorphism - Summary Virtual functions can be invoked with all object types of a hierarchy and adjust appropriately for the corresponding type. Thus a virtual function can take many forms – a mechanism referred to as polymorphism. Virtual functions and polymorphism are fundamental for the generic programming approach that aims at producing code independent of type. Binding is the process of resolving which of a set of functions should be used with a given object (based on the type, of course). If the decision is made at compile time the binding is static, and if it is made at run time the binding is dynamic. Dynamic binding in C++ is achieved by calling a virtual function with a base class pointer that points to some class object (base or derived ). The function of the object the pointer points to is called, i.e. if the object is of derived class type the derived class virtual method is called even though the pointer is of base type.

20 12/08/08MET CS 563 - Fall 2008 10. Polymorphism Polymorphism - Summary Polymorphism - Summary (continued) Pure virtual functions are functions with no definition in the class they are first declared. They are declared by appending "=0" at the end of the prototype. A full definition is eventually provided in some of the derived classes so that the virtual function can be executed. An abstract class is a class that has at least one pure virtual function. No objects of abstract class type can be instantiated. Abstract classes serve to define general categories for structuring the programs. A concrete class is a class for which objects can be instantiated. It is typically derived from some abstract class whose attributes it inherits.


Download ppt "12/08/08MET CS 563 - Fall 2008 10. Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as."

Similar presentations


Ads by Google