Weird behaviour of C++ pure virtual classes
Please help a bloody C++-beginner understand pure virtual classes better.
I tried a simple example with C++ virtuals and am not sure about the result. If I tried the same in another programming language as java for example the output would be
Desired/Expected Output
1 -> Tweet
2 -> Tweet
However, here the output is
Actual Output
1 -> Meow
2 -> Tweet
Why is that? It seems as if the operator= of the class animal had no effect. Is that because a standard operator= of the class animal is called which just does nothing? How would I achieve a behaviour similiar to java without having to use pointers? Is that even possible?
Below an as simplified as possible example of code:
Code
#include <string>
#include <iostream>
using namespace std;
class Animal
{
public:
virtual string test() const = 0;
};
class Cat : public Animal
{
public:
virtual string test() const
{
return "Meow";
}
};
class Bird : public Animal
{
public:
virtual string test() const
{
return "Tweet";
}
};
void test_method(Animal &a)
{
Bird b;
a = b;
cout << "1 -> " << a.test() << endl;
cout << "2 -> " << b.test() << endl;
}
int main(int args, char** argv)
{
Cat c;
Animal &a = c;
test_method(a);
return 0;
}