Polymorphism in C++
Polymorphism in C++
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a same time is a father, a husband, a employee. So a same person posses have different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a same time is a father, a husband, a employee. So a same person posses have different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
- Compile time Polymorphism
- Runtime Polymorphism
- Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.
- Function Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.
// C++ program for function overloading
#include <bits/stdc++.h>
using
namespace
std;
class
Geeks
{
public
:
// function with 1 int parameter
void
func(
int
x)
{
cout <<
"value of x is "
<< x << endl;
}
// function with same name but 1 double parameter
void
func(
double
x)
{
cout <<
"value of x is "
<< x << endl;
}
// function with same name and 2 int parameters
void
func(
int
x,
int
y)
{
cout <<
"value of x and y is "
<< x <<
", "
<< y << endl;
}
};
int
main() {
Geeks obj1;
// Which function is called will depend on the parameters passed
// The first 'func' is called
obj1.func(7);
// The second 'func' is called
obj1.func(9.132);
// The third 'func' is called
obj1.func(85,64);
return
0;
}
Output:value of x is 7 value of x is 9.132 value of x and y is 85, 64
In the above example, a single function named func acts differently in three different situations which is the property of polymorphism. - Operator Overloading: C++ also provide option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two strings. We know that this is the addition operator whose task is to add to operands. So a single operator ‘+’ when placed between integer operands , adds them and when placed between string operands, concatenates them.
Example:// CPP program to illustrate
// Operator Overloading
#include<iostream>
using
namespace
std;
class
Complex {
private
:
int
real, imag;
public
:
Complex(
int
r = 0,
int
i =0) {real = r; imag = i;}
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator + (Complex
const
&obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return
res;
}
void
print() { cout << real <<
" + i"
<< imag << endl; }
};
int
main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
// An example call to "operator+"
c3.print();
}
Output:12 + i9
In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition operator and can add two numbers(integers or floating point) but here the operator is made to perform addition of two imaginary or complex numbers.
- Function Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.
- Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
- Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
// C++ program for function overriding
#include <bits/stdc++.h>
using
namespace
std;
// Base class
class
Parent
{
public
:
void
print()
{
cout <<
"The Parent print function was called"
<< endl;
}
};
// Derived class
class
Child :
public
Parent
{
public
:
// definition of a member function already present in Parent
void
print()
{
cout <<
"The child print function was called"
<< endl;
}
};
//main function
int
main()
{
//object of parent class
Parent obj1;
//object of child class
Child obj2 = Child();
// obj1 will call the print function in Parent
obj1.print();
// obj2 will override the print function in Parent
// and call the print function in Child
obj2.print();
return
0;
}
Output:The Parent print function was called The child print function was called
Virtual Function in C++
A virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class.When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
- Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.
- They are mainly used to achieve Runtime polymorphism
- Functions are declared with a virtual keyword in base class.
- The resolving of function call is done at Run-time.
Rules for Virtual Functions
- They Must be declared in public section of class.
- Virtual functions cannot be static and also cannot be a friend function of another class.
- Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
- The prototype of virtual functions should be same in base as well as derived class.
- They are always defined in base class and overridden in derived class. It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used.
- A class may have virtual destructor but it cannot have a virtual constructor.
Compile-time(early binding) VS run-time(late binding) behavior of Virtual Functions
Consider the following simple program showing run-time behavior of virtual functions.
// CPP program to illustrate // concept of Virtual Functions #include<iostream> using namespace std; class base { public : virtual void print () { cout<< "print base class" <<endl; } void show () { cout<< "show base class" <<endl; } }; class derived: public base { public : void print () { cout<< "print derived class" <<endl; } void show () { cout<< "show derived class" <<endl; } }; int main() { base *bptr; derived d; bptr = &d; //virtual function, binded at runtime bptr->print(); // Non-virtual function, binded at compile time bptr->show(); } |
Output:
print derived class show base class
Explanation: Runtime polymorphism is achieved only through a pointer (or reference) of base class type. Also, a base class pointer can point to the objects of base class as well as to the objects of derived class. In above code, base class pointer ‘bptr’ contains the address of object ‘d’ of derived class.
Late binding(Runtime) is done in accordance with the content of pointer (i.e. location pointed to by pointer) an Early binding(Compile time) is done according to the type of pointer, since print() function is declared with virtual keyword so it will be binded at run-time (output is print derived class as pointer is pointing to object of derived class ) and show() is non-virtual so it will be binded during compile time(output is show base class as pointer is of base type ).
NOTE: If we have created virtual function in base class and it is being overrided in derived class then we don’t need virtual keyword in derived class, functions are automatically considered as virtual functions in derived class.
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class.For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape, but we know every derived class must have implementation of draw(). Similarly an Animal class doesn’t have implementation of move() (assuming that all animals move), but all animals must know how to move. We cannot create objects of abstract classes.
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration. See the following example.
// An abstract class class Test { // Data members of class public : // Pure Virtual Function virtual void show() = 0; /* Other members */ }; |
A complete example:
A pure virtual function is implemented by classes which are derived from a Abstract class. Following is a simple example to demonstrate the same.
A pure virtual function is implemented by classes which are derived from a Abstract class. Following is a simple example to demonstrate the same.
#include<iostream> using namespace std; class Base { int x; public : virtual void fun() = 0; int getX() { return x; } }; // This class ingerits from Base and implements fun() class Derived: public Base { int y; public : void fun() { cout << "fun() called" ; } }; int main( void ) { Derived d; d.fun(); return 0; } |
Output:
fun() called
Some Interesting Facts:
1) A class is abstract if it has at least one pure virtual function.
1) A class is abstract if it has at least one pure virtual function.
2) We can have pointers and references of abstract class type.
3) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
4) An abstract class can have constructors.
Virtual Base Class
What is a virtual base class?
- An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class.
- C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is avoided regardless of the number of paths that exist to the child class.
- C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is avoided regardless of the number of paths that exist to the child class.
What is Virtual base class? Explain its uses.
- When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the base class’ name with the word virtual.
- Consider the following example :
- Consider the following example :
class A
{
public:
int i;
};
class B : virtual public A
{
public:
int j;
};
class C: virtual public A
{
public:
int k;
};
class D: public B, public C
{
public:
int sum;
};
int main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << “Value of i is : ”<< ob.i<<”\n”;
cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<< ob.k<<”\n”;
cout << “Sum is : ”<< ob.sum <<”\n”;
return 0;
}
{
public:
int i;
};
class B : virtual public A
{
public:
int j;
};
class C: virtual public A
{
public:
int k;
};
class D: public B, public C
{
public:
int sum;
};
int main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << “Value of i is : ”<< ob.i<<”\n”;
cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<< ob.k<<”\n”;
cout << “Sum is : ”<< ob.sum <<”\n”;
return 0;
}
Comments
Post a Comment