Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Lab 12 1. Introduction This week’s lesson is focused on Polymorphism, for which

ID: 3818275 • Letter: L

Question

Lab 12

1. Introduction

This week’s lesson is focused on Polymorphism, for which you will create classes using inheritance

and virtual functions. To start with, what is polymorphism? Polymorphism allows the name of a

function to invoke a response on a base-class-type object and a different one in objects of a derived

class, for which virtual functions are used.

1.1 Exercise 1

This exercise deals with using virtual functions, seeing how they act according to the object on

which it is applied, which you will see in main(). Create a file lab12p1.cpp and enter the following

code:

class Employee

{

protected: double sal; //salary base

public: Employee(double s){ sal=s;}

double Payment(){ return sal;}

void prt(){

cout << "Salary="<< Payment() <<endl; } };

class Manager : public Employee

{ double inc;

public: Manager(double s, double i) : Employee(s)

{ inc = i; } double Payment(){ return sal*inc; }

};

void main()

{ Employee e1(1500); Manager m1(1500, 1.5); cout << “Exercise

about inheritance and polymorphism”<<endl;

e1.prt(

);

m1.prt(

); }

Compile the project and run it, observing what is printed on the console. Next, add the word

virtual before the function Payment() in the base class and run again the program. What happens

this time? Why?

Explanation / Answer

Warm up exlplanation :
         The 'virtual' keyword enables polymorphism which allows to actually override functions. Just inheriting any function is not overriding, in C++. So we use have to explicitly 'virtual' keyword is must to implement dyanamic polymorphism.

Output :
Exercise about inheritance and polymorphism
Salary=1500
Salary=1500

   In this case, both the calls are made to the Payment() method of the base class 'Employee'. Here the base class is Employee and derived class is Manager.
And let's just say that 'e1' and 'm1' are their instances respectively. When you call m1.Payment(), and if the 'Payment' method of the base class is not virtual, then the Payment() method from base class Employee gets executed, ignoring the fact that m1 is an instance of to Manager. Payment method from the from Manager class will not get called. Without using virtual keyword, 'early binding' happens, meaning that which implementation of a method to be used gets decided during compilation. So, the call is binded to the method from the base class.

Output :
Exercise about inheritance and polymorphism
Salary=1500
Salary=2250

   With "virtual" you get "dynamic binding" and the implementation of the method is used gets decided at run time based on the type of the object pointed to. In this case when you invoke m1.Payment() it calls the Payment method from Manager class, not from the base class Employee.