I faced a confusing behavior. I can't understand why this code behave like this.
#include <iostream>
#include <cstdlib>
struct A {
virtual void test() = 0;
};
struct B : public A {
void test() override { std::cout << "B" << std::endl; }
};
struct C : public A {
void test() override { std::cout << "C" << std::endl; }
};
int main()
{
A* b = new B();
A* c = new C();
A* t = b;
t->test();
t = c;
t->test();
}
It will work to put out this.
B
C
But, this code work like this.
#include <iostream>
#include <cstdlib>
struct A {
virtual void test() = 0;
};
struct B : public A {
void test() override { std::cout << "B" << std::endl; }
};
struct C : public A {
void test() override { std::cout << "C" << std::endl; }
};
int main()
{
A* b = new B();
A* c = new C();
A& t = *b;
t.test();
t = *c;
t.test();
}
B
B
I expected to return this code will put out the first code. But not. I can't understand why the second code doesn't put out like the first code. Would you mind letting me know the reason of this behavior?