Types of polymorphism in C++ with example
Hello, student today we learn about How many types of polymorphism in C++ with example and how polymorphism performs its task in C++. types of polymorphism in C with example
Polymorphism in C++ with example
#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(); }
print derived class
show base class
What is Polymorphism
We have a pointer holding the object of the derived class, virtual functions will bind at run time, which means what overrides the base class virtual function will be called, and non-virtual functions will be called as per normal object
DISCUSSION
yes, I am able to understand runtime polymorphism and compiler time polymorphism.
Another issue is if i change statement to B& ra1= static_cast(objB); then compilation error.. it’s upcast and upcast is safe… but changing the type of ra1 causes compile-time error why?
Ans:- it should complain coz the derived class should not be able to access the base class.
Swap node of the doubly linked list without swapping data Pairs in C++ (clickhere)
Polymorphism in C++
In simple words, polymorphism is a Role or character of things, another word A kid made each time different role like Student, son, friend, boys, etc.
Types of Polymorphism in C++
1. Compile time Polymorphism
When an object is bound with its functionality when Compiling, that is called compile-time polymorphism. There are two types:-
- Function Overloading:- More than two functions having the same name with different parameters; such functions are known as function overloading.
- Operator Overloading:- C++ allows us to changes the way that operators work for user-defined types like structures and Objects. That is called operator overloading.
2. Runtime Polymorphism
This polymorphism is also known as dynamic polymorphism. In runtime polymorphism, the function call is resolved at run time.
- viRtual Function:- Virtual functions are member functions whose behavior can be overridden in derived classes.
I hope you Will understand all about Polymorphism types of polymorphism in C++ for example.