polymorphism

This commit is contained in:
Timo Hocker 2020-05-24 17:39:59 +02:00
parent 804adb3b89
commit 0d55cf1273
9 changed files with 28 additions and 9 deletions

View File

@ -15,9 +15,9 @@ Lessons:
- [creating a class](./lessons/Classes.md)
- [constructors](./lessons/Constructors.md)
- [encapsulation](./lessons/Encapsulation.md)
- [inheritance](./lessons/Inheritance.md) <--
- [properties](./lessons/Properties.md)
- [polymorphism](./lessons/Polymorphism.md)
- [inheritance](./lessons/Inheritance.md)
- [properties](./lessons/Properties.md) -
- [polymorphism](./lessons/Polymorphism.md) -
Work in progress:

5
cpp/Polymorphism.md Normal file
View File

@ -0,0 +1,5 @@
# Polymorphism
Relevant files:
- [main.cpp](./inheritance/main.cpp)

View File

@ -5,8 +5,6 @@ little to complicated for this lesson.
Relevant files:
- [main.cpp](./index.cpp)
- [animal.h](./animal.h)
- [animal.cpp](./animal.cpp)

View File

@ -7,6 +7,7 @@ class animal
{
public:
std::string name;
// define make_sound as virtual to allow overriding in subclasses
virtual void make_sound();
animal(std::string name);
};

View File

@ -4,6 +4,9 @@
#include <string>
void cat::make_sound() {
// call the base class function first
animal::make_sound();
// add additional functionality
cout << "meow" << endl;
}

View File

@ -1,12 +1,15 @@
#pragma once
#include <string>
// include the animal header
#include "animal.h"
using namespace std;
class cat: public animal
{
// include the animal constructor
using animal::animal;
public:
// override the make_sound function
void make_sound() override;
};

View File

@ -4,6 +4,7 @@
#include <string>
void dog::make_sound() {
// implement own functionality
cout << "doggo " << name << " says:" << endl;
cout << "woof!" << endl;
}

View File

@ -1,12 +1,15 @@
#pragma once
#include <string>
// include the animal header
#include "animal.h"
using namespace std;
class dog: public animal
{
// include the animal constructor
using animal::animal;
public:
// override the make_sound function
void make_sound() override;
};

View File

@ -1,12 +1,17 @@
#include "animal.h"
#include "cat.h"
#include "dog.h"
#include <string>
int main() {
dog d("buster");
cat c("mittens");
// because cat and dog are subclasses of animal, they can be stored in an array of animals
animal * animals[2] = {
new dog("buster"),
new cat("mittens")
};
d.make_sound();
c.make_sound();
for (animal * a : animals)
// when calling the make_sound function, the implementation of the actual class gets called (in this case cat or dog)
a->make_sound();
}