3

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!

lwxted
  • 2,419
  • 2
  • 16
  • 22

1 Answers1

1

In the first case you're doing something wrong: slicing which is "cutting away part of the object" since you're assigning a derived object to a base object. You're not using virtual polymorphism because you're just calling methods on a "sliced" derived object (which isn't even safe).

Virtual polymorphism works with base class pointers to derived objects and virtual functions overriding, and that is a safe, runtime, mechanism to specialize your objects and call the appropriate methods.

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246