Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class Animal {
- public:
- Animal(const char * name) : name(name) {};
- private:
- const char * name;
- };
- class Dog : public Animal {
- public:
- Dog(const char * name) : Animal(name) {};
- void Pet() { // here the function is called on the dog abstraction
- Petted(); // dynamically dispatched to the run-time type.
- }
- protected:
- virtual void Petted() {
- std::cout << "You petted a random Dog!" << std::endl;
- }
- private:
- };
- class Snoopy : public Dog {
- bool is_tired;
- public:
- Snoopy() : Dog("Snoopy") {};
- protected:
- virtual void Petted() {
- if (is_tired) {
- std::cout << "You petted Snoopy but he is tired" << std::endl;
- } else {
- std::cout << "You petted Snoopy!" << std::endl;
- std::cout << "Snoopy: Bark Bark!";
- }
- }
- };
- void pet_a_dog(Dog* dog) { // here we can reference Dog*
- dog->Pet(); // pet a Dog* but resolved to Snoopy.
- }
- int main() {
- Dog* snoopy = new Snoopy();
- pet_a_dog(snoopy);
- delete snoopy;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement