diff --git a/.gitignore b/.gitignore index 9e34881..3530b24 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ accumulate object-lifetime shared_ptr casts +classes diff --git a/CMakeLists.txt b/CMakeLists.txt index abc36be..2256cd5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,3 +14,4 @@ add_executable(accumulate accumulate.cpp) add_executable(object-lifetime object-lifetime.cpp) add_executable(shared_ptr shared_ptr.cpp) add_executable(casts casts.cpp) +add_executable(classes classes.cpp) diff --git a/classes.cpp b/classes.cpp new file mode 100644 index 0000000..825b257 --- /dev/null +++ b/classes.cpp @@ -0,0 +1,41 @@ +#include +#include + +class Animal { + public: + // Note: using *virtual* does the difference here! + virtual void makeSound() { + std::cout << "" << std::endl; + } +}; + +class Cow : public Animal { + public: + void makeSound() { + std::cout << "Mooh." << std::endl; + } +}; + +class Cat : public Animal { + public: + void makeSound() { + std::cout << "Meow?" << std::endl; + } +}; + +int main() { + Cat cat; + Cow cow; + + // Does nothing: + std::vector animals = { cat, cow }; + for (auto &a: animals) { + a.makeSound(); + } + + // Meow? Mooh. + std::vector animalptrs = { &cat, &cow }; + for (auto &a: animalptrs) { + a->makeSound(); + } +}