Consider the following code:
class A {
public:
virtual void hello() { std::cout << "Hello from A" << std::endl; }
void hi() { std::cout << "Hi from A" << std::endl; }
};
class B : public A {
public:
void hello() { std::cout << "Hello from B" << std::endl; }
void hi() { std::cout << "Hi from B" << std::endl; }
};
int main() {
A foo = B();
foo.hello(); // prints "Hello from A"
foo.hi(); // prints "Hi from A";
A *bar = new B();
bar->hello(); // prints "Hello from B"
bar->hi(); // prints "Hi from A"
}
I'm aware that since hello() is declared as a virtual function in class A, any object of class B should have overridden behavior. However, why doesn't the object foo call the overridden hello()?
In other words, in what ways are the two object construction methods different? A foo = B(); v/s A *bar = new B()?
Thanks!