Lec10 Function+ +Polymorphism

download Lec10 Function+ +Polymorphism

of 42

Transcript of Lec10 Function+ +Polymorphism

  • 8/6/2019 Lec10 Function+ +Polymorphism

    1/42

    Nisar Ahmad

    Lec#10

    July 5, 2011

    Computer Science Department

    National University of Computer and Emerging SciencesIslamabad

    Programming for Engineers-IIVirtual Functions & Polymorphism

  • 8/6/2019 Lec10 Function+ +Polymorphism

    2/42

    Interesting Facty

    Pointer of a base class can hold addresses of objects of itsderived classesy Consider Point and Circle classes of previous lectureclass Point {

    //implementation };class Circle: public Point {

    //implementation };

    void main( void ){Point *p = new Circle(3,3,2.5);

    }A

    bove code is correct. Is there any problem?

    YES: If we call Displayfunction through p then which

    function will execute

  • 8/6/2019 Lec10 Function+ +Polymorphism

    3/42

    Example

    Consider following client code:void main( ){

    Point *ptr = new Circle(3,3,2.5);ptr->Display();

    }A lthoughptr is pointing to aCircle s object but itwill call Display function of Point class instead of calling Circles Display function. Why? Solution?

  • 8/6/2019 Lec10 Function+ +Polymorphism

    4/42

    Assignment to the Base class pointery

    C++ allows to assign the address of a derived class toa base class pointer because it is safe to use such apointer.

    y The base class pointer can be used to access onlymembers defined within the base class.

    y A ll these members are also defined within thederived class(by inheritance); therefore, if the pointercontains the address of a derived class object, anymember that can be referenced with the pointer will be defined.

  • 8/6/2019 Lec10 Function+ +Polymorphism

    5/42

    Assignment to the Base class pointer

    y ptr->Display();y Will always call thebase class Display() function.

    y Compiler doesnt know what class the contents of ptr may contains.

    y Compiler ignores the contents of the pointerptrand chooses the member function that matches thetype of the pointer.

  • 8/6/2019 Lec10 Function+ +Polymorphism

    6/42

    S tatic Binding vs. Late Binding

    y Choosing function in the normal way duringcompilation, is called Early Binding.

    y A t run time, when it is known what class ispointed to by ptr, the appropriate version of Display will be called. This is called LateBinding or Dynamic Binding.y Choosing the appropriate function to call at

    execution time (rather than at compile time)

  • 8/6/2019 Lec10 Function+ +Polymorphism

    7/42

    Virtual Functionsy Problem can be solved by declaring Display

    function in base class as virtual function

    y Runtime binding (Dynamic binding) of objectwith function depending upon type of object

    y In above example we should declare Displayfunction of Point class as virtual.y virtual void Display();

  • 8/6/2019 Lec10 Function+ +Polymorphism

    8/42

    Virtual Functions

    Can be invoked via either a dereferenced pointer or areference objectA ctual function to be invoked is determined from thetypeof object that is stored at the memory location being accessed

    Definition of the derived function overrides the definition of the base class version

    Determination of which virtual function to use cannot always be made at compile time

    Decision is deferred by the compiler to run timeIntroduces overhead

  • 8/6/2019 Lec10 Function+ +Polymorphism

    9/42

    Virtual Functions

    y O nce a function is declared virtual, it remainsvirtual all the way down the inheritance hierarchyfrom that point, even if that function is not explicitlydeclared virtual when a class overrides it.

    y Even though certain functions are implicitly virtual

    because of a declaration made higher in the classhierarchy, explicitly declare these functions virtual atevery level of the hierarchy to promote programclarity.

  • 8/6/2019 Lec10 Function+ +Polymorphism

    10/42

    Example of S hape Classy

    Consider the hierarchy of shape classy Shapey Two dimensional shape

    y R ectangle , square , Circle etc.y Three dimensional shape

    y Cube , parallelogram , sphere etc.y We want to usesame message fordrawing all

    objects, even when they are stored in base classpointer variable

    y DeclareDraw method asvirtual in Shape class,andoverride it inchild classes

  • 8/6/2019 Lec10 Function+ +Polymorphism

    11/42

    Polymorphismy Polymorphism is a powerful feature of the object oriented

    programming language C++.

    y Polymorphism enables us to "program in the general"rather than "program in the specific.

    y Execution of different functions by sending same message .

    y A single operator + behaves differently in different contextssuch as integer, float or strings referring theconcept of polymorphism (operator overloading ).

    y The concept of overloading is also a branchof polymorphism .

  • 8/6/2019 Lec10 Function+ +Polymorphism

    12/42

    Polymorphismy

    In polymorphism, a single function or an operator functioning in many ways depends upon the usage tofunction properly. In order for this to occur, thefollowing conditions must apply:y All different classes must be derived from a single base

    class. In the example, the shapes of objects (circle,triangle, rectangle) are from the single base class calledShape.

    y The member function must be declared virtual in the base class. In the above example, the member function for making the object should be made as virtual to the base

    class.

  • 8/6/2019 Lec10 Function+ +Polymorphism

    13/42

    Ty pes of Pol ymorphismy C++ provides three different types of polymorphism:

    1. Virtual Functions2. Function Name Overloading3. Operator Overloading

  • 8/6/2019 Lec10 Function+ +Polymorphism

    14/42

    Ab stract b ase classes and Concrete Classes

    y Class is a type , and it is assumed that objects of this type will be created

    y But actually creating instance of all classes is not

    requiredy Classes for which programmer never intends to

    create an object , are called abstract classes(abstract base classes )

    y Objects of abstract base classes can NO T becreated

    y Classes from which objects CA N be instantiatedare called concrete classes

  • 8/6/2019 Lec10 Function+ +Polymorphism

    15/42

    M aking a class as Ab stract Base Classy

    In C++ a class can be made as abstract by declaring itsat least one of the member functions as pure virtualfunction

    y

    So to make Shape class as abstract class, we have todeclare at least its one of the functions as pure virtualfunction

    y

    A function can be made as pure virtual function byinitializing function with 0. For example to make Drawfunction as virtual:

    virtual void Draw(void) = 0;

  • 8/6/2019 Lec10 Function+ +Polymorphism

    16/42

    D erived-Class M em b er-Function Callsvia Base-Class Pointers

    y H andle (pointer/reference)y Base-pointer can aim at derived-object

    y But can only call base-class functionsy Calling derived-class functions is a compiler

    error y Functions not defined in base-class

    y C ommon themey Data type of pointer/reference determines

    functions it can call

  • 8/6/2019 Lec10 Function+ +Polymorphism

    17/42

    Ab stract Classesy A bstract classes not required, but helpfuly To make a class abstract

    y Need one or more "pure" virtual functionsy Declare function with initializer of 0

    virtual void draw() = 0;y Regular virtual functions

    y Have implementations, overriding is optionaly Pure virtual functions

    y No implementation, must be overriddeny A bstract classes can have data and concrete

    functionsy Required to have one or more pure virtual functions

  • 8/6/2019 Lec10 Function+ +Polymorphism

    18/42

    A S hape Ab stract Base Class

    class Shape {public:

    Shape();int GetColor() const ;void SetColor( const int &c);virtual void Draw() = 0; // pure virtual function!

    private :int Color;

    };

  • 8/6/2019 Lec10 Function+ +Polymorphism

    19/42

    Case S tudy: Payroll S ystem Using Polymorphism

    y Create a payroll programy Use virtual functions and polymorphism

    y Problem statementy 4 types of employees, paid weekly

    1. Salaried (fixed salary, no matter the hours)2. Hourly workers3. Commission ( paid percentage of sales)4. Base-plus-commission ( base salary +

    percentage of sales)

  • 8/6/2019 Lec10 Function+ +Polymorphism

    20/42

    Case S tudy: Payroll S ystem Using Polymorphism

    y Base class E mplo yeey Pure virtual function earnings (returns pay)

    y Pure virtual because need to know employee typey Cannot calculate for generic employee

    y Other classes derive from E mplo yeeEmploy ee

    Sa l ariedEmploy ee Ho ur ly Employ eeComm issi o nEmploy ee

    BaseP l usC omm issi onEmploy ee

  • 8/6/2019 Lec10 Function+ +Polymorphism

    21/42

    Employee: Ab stract b ase class example1. class Employee {2 . public :3 . Employee( const char *, const char *);4 . ~ Employee();5 . char *getFirstName() const ;

    6 . char *getLastName() const ;7 . // Pure virtual functions make Employee

    abstract base class .8. virtual float earnings() const = 0; // pure virtual9 . virtual void print() const = 0; // pure virtual1 0 .protected :11. char *firstName;1 2 . char *lastName;1 3 .};

  • 8/6/2019 Lec10 Function+ +Polymorphism

    22/42

    1. Employee::Employee( const char *first, const char *last)2 . {3 . f irstName = new char [ strlen( f irst) + 1 ];4 . strcpy( f irstName, f irst);5 . lastName = new char [ strlen(last) + 1 ];6 . strcpy(lastName, last);7 . }

    8. // Destructor deallocates dynamically allocated memory9 . Employee:: ~ Employee() {1 0 . delete [] f irstName; delete [] lastName;11. }

    1 2 . // Return a pointer to the f irst name1 3 . char *Employee::getFirstName() const {1 4 . return f irstName; // caller must delete memory1 5 . }

    1 6 . char *Employee::getLastName() const {1

    7.

    return lastName; // caller must delete memory18. }

  • 8/6/2019 Lec10 Function+ +Polymorphism

    23/42

    1. class SalariedEmployee: public Employee {2. public :3. SalariedEmployee( const char *, const char *,

    float = 0.0);4. void setWeeklySalary( float );

    5. virtual float earnings() const ;6. virtual void print() const;

    7. private :8. float weeklySalary;9. };

  • 8/6/2019 Lec10 Function+ +Polymorphism

    24/42

    1. // Constructor function2. SalariedEmployee::

    3. SalariedEmployee( const char *first, const char *last, float s)4. : Employee(first, last) // call base-class constructor5. {6. weeklySalary = s > 0 ? s : 0;7. }

    8. // Set the SalariedEmployee s salary9. void SalariedEmployee::setWeeklySalary( float s)10. {11. weeklySalary = s > 0 ? s : 0;12. }

  • 8/6/2019 Lec10 Function+ +Polymorphism

    25/42

    12. // Get the SalariedEmployee s pay

    13. float SalariedEmployee::earnings() const 14. {15. return weeklySalary;16. }

    17. // Print the SalariedEmployee s name18. void SalariedEmployee::print() const 19. {

    20. cout

  • 8/6/2019 Lec10 Function+ +Polymorphism

    26/42

    1. class CommissionWorker : public Employee {2. public :

    3. CommissionWorker( const char *, const char *,4. float = 0.0, unsigned = 0);5. void setCommission( float );6. void setQuantity( unsigned );

    7. virtual float earnings() const ;8. virtual void print() const ;

    9. private :

    10. float commission; // amount per item sold11. unsigned quantity; // total items sold for week12. };

  • 8/6/2019 Lec10 Function+ +Polymorphism

    27/42

    1. CommissionWorker::CommissionWorker( const char *first,const char *last, float c, unsigned q)

    : Employee(first, last) // call base-class constructor2. {3. commission = c > 0 ? c : 0;4. quantity = q > 0 ? q : 0;5. }6. void CommissionWorker::setCommission( float c)

    7. { commission = c > 0 ? c : 0; }8. void CommissionWorker::setQuantity( unsigned q)9. { quantity = q > 0 ? q : 0; }

    10. float CommissionWorker::earnings() const 11. { return commission * quantity; }

    12. void CommissionWorker::print() const 13. {14. cout

  • 8/6/2019 Lec10 Function+ +Polymorphism

    28/42

    1. class HourlyWorker : public Employee2. {3. public :4. HourlyWorker( const char *, const char *,

    float = 0.0, float = 0.0);5. void setWage( float );6. void setHours( float );7. virtual float earnings() const ;8. virtual void print() const ;

    9. private :10. float wage; // wage per hour11. float hours; // hours worked for week12. };

  • 8/6/2019 Lec10 Function+ +Polymorphism

    29/42

    1. HourlyWorker::HourlyWorker( const char *first, const char *last,float w, float h) : Employee(first, last) // call base-class constructor

    2. {3. wage = w > 0 ? w : 0;4. hours = h >= 0 && h < 168 ? h : 0;5. }

    6. void HourlyWorker::setWage( float w)7. { wage = w > 0 ? w : 0; }

    8. // Set the hours worked9. void HourlyWorker::setHours( float h)10. { hours = h >= 0 && h < 168 ? h : 0; }

    11. // Get the HourlyWorker's pay

    12. float HourlyWorker::earnings() const 13. { return wage * hours; }

    14. // Print the HourlyWorker's name15. void HourlyWorker::print() const 16. { cout

  • 8/6/2019 Lec10 Function+ +Polymorphism

    30/42

    1. class BasePlusCommissionEmployee: public CommissionWorker2. {3. private :4. float baseSalary;5. public :6. BasePlusCommissionEmployee( const char * , const char * ,

    float =0.0, unsigned =0, float =0.0);7. void setBaseSalary( float sal)

    8. {9. baseSalary = sal;10. }

    11. float getBaseSalary( void) const 12. {13. return baseSalary;14. }

    15. void print() const ;16. float earnings() const ;17. };

  • 8/6/2019 Lec10 Function+ +Polymorphism

    31/42

    1. BasePlusCommissionEmployee::BasePlusCommissionEmployee( const char * f irst, const char * last, f loat c, unsigned q, f loat sal):CommissionWorker( f irst, last, c, q)

    2 . {3 . baseSalary=sal;4 . }

    5 . void BasePlusCommissionEmployee::print() const6 . {7 . cout

  • 8/6/2019 Lec10 Function+ +Polymorphism

    32/42

    1. void main( void)2. {3. Employee *ptr; // base-class pointer

    4. SalariedEmployee b("Nauman", "Sarwar", 800.00);5. ptr = &b; // base-class pointer to derived-class object 6. ptr->print(); // dynamic binding7. cout

  • 8/6/2019 Lec10 Function+ +Polymorphism

    33/42

    1. BasePlusCommissionEmployee p("Madiha", "Mustafa", 2.5, 200,1000.0);

    2. ptr = &p; // base-class pointer to derived-class object 3. ptr->print(); // dynamic binding

    4. cout

  • 8/6/2019 Lec10 Function+ +Polymorphism

    34/42

    O utputSalaried Employee: Nauman Sarwar earned $800.00Salaried Employee: Nauman Sarwar earned $800.00

    Commission Worker: Qasim Ali earned $450.00Commission Worker: Qasim Ali earned $450.00

    Base-salaried commission employee:Commission Worker: Madiha Mustafa earned $1500.00Base-salaried commission employee:

    Commission Worker: Madiha Mustafa earned $1500.00HourlyWorker: Saima Tufail earned $550.00HourlyWorker: Saima Tufail earned $550.00

  • 8/6/2019 Lec10 Function+ +Polymorphism

    35/42

    Virtual D estructor

    y If a derived-class object with a non-virtualdestructor is destroyed explicitly byapplying the delete operator to a base-class

    pointer to the object, the C++ standardspecifies that the behavior is undefined .

    y S olutiony Create a virtual destructor (i.e., a

    destructor that is declared with keywordvirtual) in the base class.

  • 8/6/2019 Lec10 Function+ +Polymorphism

    36/42

    Virtual D estructor

    Now, if an object in the hierarchy isdestroyed explicitly by applying the deleteoperator to a base-class pointer, thedestructor for the appropriate class iscalled based on the object to which the

    base-class pointer points.

    Constructors cannot be virtual. Declaringa constructor virtual is a compilation error.

  • 8/6/2019 Lec10 Function+ +Polymorphism

    37/42

    Example without using virtual D estructor# include

    class Base{

    public :Base(){ cout

  • 8/6/2019 Lec10 Function+ +Polymorphism

    38/42

    Example without using virtual D estructor

    void main(){

    Base *Var = new Derived();

    delete Var;}

    O utput:Constructor: BaseConstructor: DerivedDestructor : Base

  • 8/6/2019 Lec10 Function+ +Polymorphism

    39/42

  • 8/6/2019 Lec10 Function+ +Polymorphism

    40/42

    Example using virtual D estructor

    void main(){

    Base *Var = new Derived();

    delete Var;}

    O utput:Constructor: BaseConstructor: DerivedDestructor : DerivedDestructor : Base

  • 8/6/2019 Lec10 Function+ +Polymorphism

    41/42

    R eferencey Chapter #13

    y C++ How to Program, Fifth EditionBy Deitel and Deitel;

  • 8/6/2019 Lec10 Function+ +Polymorphism

    42/42

    y Create abstract base classShapey pure virtual function Draw();

    y Derived classesy Circle

    y int radiusy Rectangle

    y int height, widthy O verride Draw functions to display the members

    y In the main program,y Create an array of Shape pointers of size 10y In the for loop of 10

    y cin an integer from user in ay If (integer is 1) create a Circle object at next array indexy Else create a Rectangle object

    y Loop through the array and call Draw functionsy Show output