Polymorphism in C++ (part 2)
In the previous blog post, the definition,types and function overloading concepts are included.
Here, is the link.
https://rajeeva84.blogspot.com/2025/11/polymorphism-in-c.html
in this post, operator overloading and run time polymorphism
using virtual functions are explained.
Operator overloading:
This
concept deals with operator. An operator can be overloaded with another
definition.
For example, “%” is used as two purposes. One is finding
‘mod’ functions and another one is ‘percentage’.
Let us create a c++ program as follows.
#include <iostream>
class ModIt {
int m_value;
public:
ModIt(int v) :
m_value(v) {}
ModIt
operator%(const ModIt& x) const {
return
ModIt(m_value % x.m_value);
}
std::cout
<<"The value is: "<< m_value << std::endl;
}
};
int x,y;
cout<<"Enter the values:"<<endl;
cin>>
x>>y;
ModIt a(x), b(y);
ModIt c = a % b;
c.displayIt();
}
Output:
Enter the values:
67 3
The value is: 1
Next one is run time polymorphism.
Run
time polymorphism deals with virtual functions in terms of function overriding.
This deals with functions at runtime.
Here, is the program.
#include <bits/stdc++.h>
using namespace std;
class bclass {
public:
// create a
Virtual function
virtual void
displayIt() {
cout <<
"This is the Base class function";
}
};
class Dclass : public bclass {
public:
// let us Override
the base class function
void displayIt()
override {
cout <<
"This is the Derived class function";
}
};
int main() {
// Creating a
pointer of bclass
bclass* bPtr;
// Creating an
object of Dclass
Dclass dObj;
// base class
pointer points to the derived class object
bPtr = &dObj;
// base class
pointer calls the displayIt() function
bPtr->displayIt();
return 0;
}
Output
This is the Derived class
function
Hope, the different types of polymorphism are easy for you.
If you have any doubts, comment in the comment section .Keep Coding!!!
Comments
Post a Comment