Skip to content

Instantly share code, notes, and snippets.

@HammadMaqbool
Created October 24, 2023 16:07
Show Gist options
  • Save HammadMaqbool/b401a7597e5c8e09d0174c690367c3eb to your computer and use it in GitHub Desktop.
Save HammadMaqbool/b401a7597e5c8e09d0174c690367c3eb to your computer and use it in GitHub Desktop.
C++ Example code to understand the concept of Polymorphish using Virtual Function
#include<iostream>
using namespace std;
class Animal
{
public:
virtual void Sound()
{
//No code. . .
}
};
//-------------------------------------
class Cat : public Animal
{
public:
void Sound()
{
cout<<"Meow Meow";
}
};
//-------------------------------------
class Dog : public Animal
{
public:
void Sound()
{
cout<<"bow bow";
}
};
//-------------------------------------
int main()
{
Cat PersianCat;
Dog Lebra;
Animal* Pet;
string Choice;
cout<<"Please tell me the Animal Name ";
cin>>Choice;
if(Choice == "Cat" || Choice == "cat" || Choice == "CAT")
{
Pet = &PersianCat;
Pet->Sound();
}
else if(Choice == "Dog" || Choice == "dog" || Choice == "DOG")
{
Pet = &Lebra;
Pet->Sound();
}
}
//Code by HammadMaqbool
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment