Skip to content

Instantly share code, notes, and snippets.

@deciduously
Last active October 26, 2019 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deciduously/fcfc449d529eb2d0563dcc2349ba2649 to your computer and use it in GitHub Desktop.
Save deciduously/fcfc449d529eb2d0563dcc2349ba2649 to your computer and use it in GitHub Desktop.
Discussion post demonstration of dynamic binding and polymorphism
/*
* Discussion post code sample
* Benjamin Lovy
*/
#include <iostream>
class Animal
{
public:
virtual void makeNoise();
};
void Animal::makeNoise()
{
std::cout << "*muffled scratching sounds*" << std::endl;
}
class Cat : public Animal
{
public:
virtual void makeNoise();
};
void Cat::makeNoise()
{
std::cout << "Meow!" << std::endl;
}
class Dog : public Animal
{
public:
virtual void makeNoise();
};
void Dog::makeNoise()
{
std::cout << "Woof!" << std::endl;
}
int main()
{
// Init generic Animal
Animal *generic = new Animal();
// Init Cat
Animal *cat = new Cat();
// Init Dog
Animal *dog = new Dog();
// Make some noise
std::cout << "Animal One: ";
generic->makeNoise();
std::cout << "Animal Two: ";
cat->makeNoise();
std::cout << "Animal Three: ";
dog->makeNoise();
delete generic;
delete cat;
delete dog;
// Exit success
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment