Polymorphism Part 1 C++
Polymorphism:
Poly means many and morph means forms. So polymorphism means having many forms.
Implementation:
Polymorphism can be implemented by:
- Function overriding
- Operator overloading
- Virtual function
Polymorphism implementation by Function overriding:
What is function overriding?
Function overriding is a feature that allows us to have the same function in child class which is already present in the base class. As we know that a child class inherits the data members and functions of the base class, but when we want to override a functionality of a function of base class in child class we can use function overriding.
For example:
Consider you make a base class named Person then you make a function of the class Person named Profession. As every child class of Person class that you make will have different profession.
#include<iostream> using namespace std; class Person{ public: void profession(){ //base class function } }; class Teacher:public Person{ public: void profession(){ // first child class overrides base class function cout<<"teaches"<<endl; } }; class Student:public Person{ public: void profession(){ //second child class overrides base class function cout<<"studies"<<endl; } }; int main() { // to call teacher class profession function Teacher t1; t1.profession(); // to call student class prfession function Student s1; s1.profession(); return 0; }
Output:
teaches
studies
teaches
studies
Points to remember:
1. Inheritance should be there. Function overriding cannot be done within a class. For this we require a derived class and a base class.
2. In C++, the base class member can be overridden by the derived class function with the same signature as the base class function.
3. Function that is redefined must have exactly the same declaration in both base and derived class, that means same name, same return type and same parameter list.
4. Method overriding is used to provide different implementations of a function so that a more specific behavior can be realized.
5. Overriding is done in child class for a method that is written in the parent class.
6. It changes the existing functionality of the method hence should be used carefully.
Thanks I love your explanation.
ReplyDeleteunderstandable
ReplyDeletesuperb explanation
ReplyDeletesuperb explanation
ReplyDelete