I am learning polymorphism and I am familiar with php.
I came across this excellent example from https://stackoverflow.com/a/749738/80353. reproduced below.
How do I write the same code, but in C++?
I have a problem writing it myself because I believe (I may be wrong) that the data structures in C++ are strict.
You must have all the elements inside a linkedlist or array in C++ of the same type.
So I believe that you need to store the cat and dog as their base class into the data structure.
So how do I write this php code snippet into a C++ code snippet that uses a strict data structure that it can only store elements of 1 data type?
class Animal {
var $name;
function __construct($name) {
$this->name = $name;
}
}
class Dog extends Animal {
function speak() {
return "Woof, woof!";
}
}
class Cat extends Animal {
function speak() {
return "Meow...";
}
}
$animals = array(new Dog('Skip'), new Cat('Snowball'));
foreach($animals as $animal) {
print $animal->name . " says: " . $animal->speak() . '<br>';
}