The class is polymorphic. Why do both print the same output?
class A
{
public:
virtual void P(){ cout << "A" << endl; }
};
class B : public A
{
public:
void P()override{
cout << "B" << endl;
}
B(){ cout << "Created B" << endl; s = "Created by B"; }
string s;
};
And main: Variant 1:
A* a = new B(); // Created B
B* b = static_cast<B*>(a);
b->P(); B
cout<<b->s<<endl; // Created by B
And variant 2:
A* a = new B();
B* b = dynamic_cast<B*>(a);
if (b){
b->P();
cout << b->s << endl; // Prints same
}