I have a very simple code that is using inheritance, and I have the same function prototype in my base and derived classes. I don't understand the last result (pB->bar()), because I thought that since pB points to a derived type object (after delete) it should invoke D::bar().
#include <iostream>
class B {
public:
virtual void foo() { std::cout << "B:foo" << std::endl; }
void bar() { std::cout << "B:bar" << std::endl; }
};
class D : public B {
public:
virtual void foo() override { std::cout << "D:foo" << std::endl; }
void bar(){ std::cout << "D:bar" << std::endl;}
};
int main() {
B* pB = new B;
pB->foo();
pB->bar();
delete pB;
pB = new D;
pB->foo();
pB->bar();
delete pB;
}
the results of this are:
B:foo
B:bar
D:foo
B:bar