Created
April 3, 2024 13:38
-
-
Save grayed/9d4f958adcf4e8062534fc17f6c54cc6 to your computer and use it in GitHub Desktop.
Virtual functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class Animal { | |
string latin_name; | |
public: | |
Animal(string latin_name) : latin_name{latin_name} {} | |
virtual ~Animal() { cerr << "Animal::~Animal called for " << latin_name << endl; } | |
virtual string get_display_name() const { return latin_name; } | |
virtual int foo() = 0; | |
friend ostream& operator<<(ostream &os, const Animal &a); | |
}; | |
class Pet : public Animal { | |
string name; | |
public: | |
Pet(string name, string latin_name) : Animal{latin_name}, name{name} {} | |
~Pet() { cerr << "Pet::~Pet called for " << name << endl; } | |
int foo() override { return 42; } | |
string get_display_name() const override | |
{ return name + '(' + Animal::get_display_name() + ')'; } | |
}; | |
ostream& operator<<(ostream &os, const Animal &a) | |
{ return os << a.get_display_name(); } | |
int main() { | |
Animal *kitty = new Pet("Mimi", "felis catus"); | |
Animal *doggy = new Animal("canis familiaris"); | |
Animal &a = *kitty; | |
cout << a << endl << *doggy << endl; | |
delete kitty; | |
delete doggy; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment