Polymorphism & Virtual Functions in C++

What is polymorphism?

Object oriented programming language supports the concept of polymorphism which is characterized by the phrase “one interface multiple methods “. In simple term polymorphism is the attribute that allows one interface to control access. in another words polymorphism means to take more than one form . For example an operation may demonstrate different behaviour according to the exact nature of situation .  For example consider operation draw a shape if there are three operands then it will draw a triangle, if there are two operands then operation will draw line. Polymorphism plays an important role in object oriented programming language by allowing objects having same internal interface.     The concept of polymorphism is implemented by using the function overloading and operator overloading. The overloaded function is selected by matching arguments types, number. This information is known at runtime to compiler so the compiler is able to select appropriate function for a call this is called as early binding or static binding. Consider another scenario where the function name & prototype is same in both the base & derived class that is function is override. In such situation appropriate function is selected at runtime this is called as runtime polymorphism.

What is Virtual Function?

In simple words we can say that Virtual Function in oops is method or function which can be overridden in inherited class by method or function, an signature is same.

#include <iostream>

class class1 {

public:

virtual void myfunction() {

cout << “I am in base class\n”;

}

};

class class2 : public class1 {

public:

void myfunction() {

cout << “I am in class2\n”;

}

};

class class3 : public class1 {

public:

void vfunc() {

cout << “I am in class3”;

}

};

 

Polymorphism in c++

 

int main()

{

Class1 *p, b;

Class2 c1;

Class3 c2;

// point to base

p = &b;

p->myfunction();

p = &c1;

p-> myfunction ();

p = &c2;

p-> myfunction ();

return 0;

}

 

What are Abstract Classes?

 

A class that contains at least one pure virtual function is said to be abstract. Because an Abstract class contains one or more functions for which there is no definition (that is, a Pure virtual function), no objects of an abstract class may be created. Instead, an abstract class constitutes an incomplete type that is used as a foundation for derived classes. Although you cannot create objects of an abstract class, you can create pointers and references to an abstract class. This allows abstract classes to support run-time polymorphism, which relies upon base-class pointers and references to select the proper virtual function.

Sourabh Bhunje

Sourabh Bhunje, B.E. IT from Pune University. Currently Working at Techliebe. Professional Skills: Programming - Software & Mobile, Web & Graphic Design, Localization, Content Writing, Sub-Titling etc. http://techliebe.com/about-us

Leave a Reply