From 823aeb304f12837367b43abee33ec955ece7077f Mon Sep 17 00:00:00 2001 From: neingeist Date: Sun, 13 Apr 2014 17:37:13 +0200 Subject: [PATCH] some more playing around with refs etc. --- classes.cpp | 54 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/classes.cpp b/classes.cpp index 825b257..2e884fc 100644 --- a/classes.cpp +++ b/classes.cpp @@ -5,34 +5,80 @@ class Animal { public: // Note: using *virtual* does the difference here! virtual void makeSound() { - std::cout << "" << std::endl; + std::cout << " from " << this << std::endl; + } + + Animal& operator= (Animal &a) { + std::cout << "lol, operator= of " << this; + std::cout << "(arg: " << &a << ")" << std::endl; + + return *this; } }; class Cow : public Animal { public: void makeSound() { - std::cout << "Mooh." << std::endl; + std::cout << "Mooh. from " << this << std::endl; } }; class Cat : public Animal { public: void makeSound() { - std::cout << "Meow?" << std::endl; + std::cout << "Meow? from " << this << std::endl; } }; +void call(Animal a) { + a.makeSound(); +} + +void callref(Animal &a) { + a.makeSound(); +} + +void callptr(Animal* a) { + a->makeSound(); +} + int main() { Cat cat; Cow cow; + std::cout << "== Some animals" << std::endl; + Animal animal; + animal.makeSound(); + call(animal); + callref(animal); + callptr(&animal); + + animal = cat; // <- lol, operator + animal.makeSound(); + call(cat); + callref(cat); // <- meow + callptr(&cat); // <- meow + + animal = cow; // <- lol, operator + animal.makeSound(); + call(cow); + callref(cow); // <- mooh + callptr(&cow); // <- mooh + + std::cout << "== refs" << std::endl; + Animal &aref = cat; + aref.makeSound(); // <- meow + aref = cow; // <- lol, operator + aref.makeSound(); // <- meow, still + + std::cout << "== vector:" << std::endl; // Does nothing: - std::vector animals = { cat, cow }; + std::vector animals = { cat, cow }; // <- Copies for (auto &a: animals) { a.makeSound(); } + std::cout << "== vector:" << std::endl; // Meow? Mooh. std::vector animalptrs = { &cat, &cow }; for (auto &a: animalptrs) {