-->

C++ Polymorphism 1

 




C++ Polymorphism

 

C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. ... You have different classes with a function of the same name, and even the same parameters, but with different implementations.

Polymorphism in C++ - GeeksforGeeks

Polymorphism in C++ - Tutorialspoint

 

Simple example on  Polymorphism

if you want to download the .cpp file 

How to download


click here 

 

 

Example:

////Name Syed Syab Ahmad Shah
////Roll number *****
////University of SWAT
////BS SE
#include <iostream>///including header fil
using namespace std;
class Enemy///creating class
{
public:////public access spacifire
virtual void attack()///creating virtual function
{
cout<<"Showing virtual function now.."<<endl;
}
};
class Ninja : public Enemy///child class and inharting parent class
{
public:
void attack()///creating funtcion
{
cout<<"i am Ninja ! Showing Ninja function now.."<<endl;
}
};
class Monster : public Enemy//child class and inharting parent class
{
public:///////////////if we comment out the below function or we remove that then the virtula function will be the output instead of it.
/* void attack()///creating funtcion
{
cout<<"i am Monster ! Showing Monster function now.."<<endl;
} */
};
int main()///creating main function
{
Ninja n;///creating objects of the child class 1
Monster m;///creating objects of the child class 2

Enemy *enemy1 = &n;///creating objects of the parent class, making pointer and assigning addresses
Enemy *enemy2 = &m;///creating objects of the parent class, making pointer and assigning addresses

///enemy1->attackPower(20);
///enemy2->attackPower(30);

n.attack();/////calling function
m.attack();/////calling function
return 0;
}