The
process of representing one Form in multiple forms is known as Polymorphism.
Here one form represent original form or original method always resides in base
class and multiple forms represents overridden method which resides in derived
classes.
Type
of polymorphism
·
Compile time polymorphism
·
Run time polymorphism
Compile
time polymorphism
In
C++ programming you can achieve compile time polymorphism in two way, which is
given below;
·
Method overloading
·
Method overriding
Method
Overloading in C++
Whenever
same method name is exiting multiple times in the same class with different
number of parameter or different order of parameters or different types of
parameters is known as method overloading. In below example method
"sum()" is present in Addition class with same name but with
different signature or arguments.
Example of Method Overloading in C++
#include<iostream.h>
#include<conio.h>
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(10, 20, 30);
}
Example of Method Overriding in C++
Method Overriding in C++
Define any method in both base class and derived class with same name,
same parameters or signature, this concept is known as method overriding. In
below example same method "show()" is present in both base and
derived class with same name and signature.
#include<iostream.h>
#include<conio.h>
class Base
{
public:
void show()
{
cout<<"Base
class";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"Derived
Class";
}
}
int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Ocuurs
d.show();
getch();
}
Run time polymorphism
Run time polymorphism
In C++ Run time
polymorphism can be achieve by using virtual function.
Virtual Function is a function in base class, which is overrided in the
derived class, and which tells the compiler to perform Late Binding on this
function.
Virtual Keyword is used to make a member function of the base class
Virtual.
#include <string>
class Animal
{
protected:
std::string m_name;
// We're making this
constructor protected because
// we don't want people
creating Animal objects directly,
// but we still want derived
classes to be able to use it.
Animal(std::string name)
: m_name(name)
{
}
public:
std::string getName() { return
m_name; }
virtual const char* speak() {
return "???"; }
};
class Cat: public Animal
{
public:
Cat(std::string name)
: Animal(name)
{
}
virtual const char* speak() {
return "Meow"; }
};
class Dog: public Animal
{
public:
Dog(std::string name)
: Animal(name)
{
}
virtual const char* speak() {
return "Woof"; }
};
void report(Animal &animal)
{
std::cout <<
animal.getName() << " says " << animal.speak() <<
'\n';
}
int main()
{
Cat cat("Fred");
Dog dog("Garbo");
Report(cat);
Report(dog);
}
No comments:
Post a Comment