C++ OBJECT ORIENTED PROGRAMMING POLYMORPHISM -Sanchit Karve born2c0de@hotmail.com REQUIREMENTS: -> Should know Inheritance in C++ That's it. But in the end I explain how the compiler implements polymorphism and so knowledge of Assembly Language will be a great help in understanding Polymorphism. Nevertheless I will still try to make the assembly explanation as simple as possible.So even if you don't know Assembly,try understanding it. I. WHAT IS POLYMORPHISM? Polymorphism is in short the ability to call different functions by just using one type of function call.It is a lot useful since it can group classes and their functions together.Polymorphism is the most important part of Object- Oriented Programming. Some people feel that if they have an idea of what classes are they have stepped in the object-oriented world.But this is not true. Polymorphism is the core of object-oriented programming and if anybody stops here he's missing out the best part of Object Oriented Programming(OOP).All this may seem a lot hard to understand but read on......you'll understand better as you keep reading. Let us now try to understand polymorphism with the help of an example.Suppose we want to draw a picture consisting of circles,squares,lines and triangles.So we can make a class Shape and create an instance of it like this: Shape *s[100]; Now all the addresses of the objects of the other classes(line,circle etc.) are stored in the Shape Array.And then to draw the Picture all we have to do is this: for(int i=0;i<=100;i++) s[i]->draw(); Now as the loop runs different draw functions of each class is called. This is great because: i. Functions from different classes are executed through the same function call. i. The Array s[] has been defined to contain shape pointers and not square or triangle pointers. This can be done by using Virtual Functions. II. VIRTUAL FUNCTIONS???????? The Literal Meaning of Virtual means to appear like something while in reality it is something else ie. when virtual functions are used, a program appears to call a function of one class but actually it may be calling a function from another class.In the previous example draw() is a virtual function since it calls different draw functions from different classes by using the same function call draw(); Now how do we know which version of draw() would be called during execution? Which draw() function would get used depends on the contents of s[i].But for this polymorphic approach to work we must satisfy the following conditions: ->The Base class must contain a draw() function which is declared virtual. ->All other classes(line,circle etc.) should be derived from the base class. Well, all this may be hard to understand in just one go so we'll start using programs that'll help us understand better.Here's the First One. #include class base //Base Class { public: void func() { cout<<"In base::func()\n"; } }; class d1:public base // Derived Class 1 { public: void func() { cout<<"In d1::func()\n"; } }; class d2:public base // Derived Class 2 { public: void func() { cout<<"In d2::func()\n"; } }; void main() { d1 d; base *b=&d; b->func(); d2 e; b=&e; b->func(); } Run this program and you would see that the output would be: In base::func() In base::func() Shouldn't this statement give an error? (b=&e;) No. Since the compiler allows a pointer of a base class to accept addresses of derived class objects.This is known as UPCASTING.Here the Compiler looks at the type of pointer b and since it belongs to the base class it calls the base class function. But now, let's make a slight modification in our program. Precede the declaration of func() in the base class with the keyword virtual so that it looks like this: virtual void func() { cout<<"In base::func()\n"; } Now Compile and Run the Program. Now the Output is: In d1::func() In d2::func() This time the Compiler looks at the contents of the pointer instead of it's type. Hence since addresses of objects of d1 and d2 classes are stored in *b the respective func() is called.But this way how does the compiler know which function to compile when it doesn't know which object's address 'b' might contain?Which version does the compiler call? Actually even the compiler does not know which function to call at compile-time. Hence it decides which function to call at run-time with the help of a table called VTABLE. Using this table the compiler finds what object is pointed by the pointer b and then calls the appropriate function. VTABLE is explained later. The method by which the compiler decides which function to call at run-time is known as late-binding or dynamic-binding. It slows down the program but makes it a lot more flexible. III. PURE VIRTUAL FUNCTIONS Now we realise that since the base class virtual function never gets called anyway we'd better keep it's body blank.But there's a better way to do this. We can change the virtual function func() in the base class to the following: virtual void func()=0; The =0 is not an assignment operator here but it is just a way of telling the compiler that the function has no body.But there is another side of this. An object of a class which contains a pure virtual function cannot be created.It seems logical enough ie. If you have classes triangle,square,circle derived from shape class we wouldn't want to make an object of the shape class.Hence the shape class should be provided with a pure virtual function.If you even try to create an object of a class containing a pure virtual function the compiler would report an error even pointing out which pure virtual function prevents you from creating an object. IV. HOW VIRTUAL FUNCTIONS WORK Using Virtual Functions is just one part of polymorphism and knowing how they work completes the other half.When the keyword 'virtual' is inserted in the declaration of the function the compiler inserts all mechanisms in the program to use Virtual Functions. Each Class has a VTABLE that stores the functions that it can access and Each class contains a VPTR which can access the VTABLE.Look at this program and the table below it and you will understand the VTABLE and the VPTR. #include class item { public: virtual void price() { printf("In item::price()\n"); } virtual void type() { printf("In item::type()\n"); } void display(); }; void item::display(){printf("In item::display()\n");} class microwave:public item { public: void price() { printf("Microwave::Price()\n"); } void type() { printf("Microwave::type()\n"); } }; class computer:public item { public: void price() { printf("Compuer::Price()\n"); } }; class radio:public item { public: void type() { printf("radio::type()\n"); } }; void main() { microwave m1; computer c1; radio r1; item *i=&m1; i->price(); i->type(); printf("\n"); i=&c1; i->price(); i->type(); i->display(); printf("\n"); i=&r1; i->price(); i->type(); printf("\n"); microwave m2; i=&m2; i->price(); i->type(); i->display(); printf("\n"); } The Output of this Program would be: Microwave::Price() Microwave::type() Compuer::Price() In item::type() In item::display() In item::price() radio::type() Microwave::Price() Microwave::type() In item::display() Now here is how the VTABLE of each class Looks Like: -------------------------------------------------------------------------------| ITEM POINTERS | OBJECTS | VTABLES | -------------------------------------------------------------------------------| i-------------> | item{VPTR}----> | &item::price() | | | &item::type() | -------------------------------------------------------------------------------| | | | i-------------> |microwave m1,m2{VPTR}| µwave::price() | | | µwave::type() | -------------------------------------------------------------------------------| | | | i-------------> | computer c1{VPTR}-> | &computer::price() | | | &item::type() | -------------------------------------------------------------------------------| | | | i-------------->| radio r1{VPTR}----> | &item::price() | | | &radio::type() | -------------------------------------------------------------------------------| First the VPTR Pointer is initialised to it's proper VTABLE by the contructor which is automatically done by the compiler.When a Virtual Function is being called the VPTR looks up the VTABLE and calls the virtual function.If the function is not present in the VTABLE [like here display()] then the function of the base class is called. So everywhere where the display function is called item::display() is called everytime.No matter how many objects of a class are created they all point to the same VTABLE of the class. V. ARE VIRTUAL FUNCTIONS OPTIONAL? Normal Function calls are called by the Assembly instruction 'call' while virtual functions require complex instructions. This takes up code space as well as execution time. Virtual Functions reduce the code's speed. Some languages like SmallTalk perform Late Binding everytime a function is called and hence SmallTalk Programs aren't fast enough. But C++ is a Superset of C where Efficiency is important and hence C++ allows both static binding as well as late binding. The default convention used is static binding so that there is no loss in speed. Don't stop using Virtual Functions in your classes just because they reduce execution speed. Infact it makes it easier to manage and code and it's advantages are more than it's disadvantages. So wherever possible use Virtual Functions in your classes. VI. MISCELLENEOUS 1) If a Virtual Function is called within a derived classes constructor or destructor then the derived function is always called. 2) If b is a base class pointer and d is a derived class pointer then b=d will copy only the base class contents and remove the derived class contents.This is known as Object Slicing and should be avoided. 3) For a Virtual Function to work the function must be present in tha base class even though it is declared virtual in the derived class. 4) Virtual Destructors can also be used and they allow execution of the derived destructor first and then it calls itself. VII. VIRTUAL BASE CLASSES Consider a situation when a 'base' class has two classes derived from it.For example derived1 and derived2. Suppose we create another class which derives itself from both the derived classes ie. derived3.Now suppose a member function of derived3 wants to access data or functions in a base class.Since derived1 and derived2 are are derived from base each inherits a copy of base.This copy is referred to as a subobject. Now when derived3 refers to the data in the base class, which of the two copies should it access? The compiler notices this ambiguous situation and reports an error. To get rid of this we should make derived1 and derived2 as virtual base classes.This is shown in the following program. #include class base { protected: int data; public: base() { data=10; } }; class derived1 : virtual public base {}; class derived2 : virtual public base {}; class derived3 : public derived1,public derived2 { public: int getdata() { return data; } }; void main() { derived3 d3; int val=d3.getdata(); cout<