Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual function behavior on statically declared objects [duplicate]

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!

like image 779
lwxted Avatar asked May 24 '26 05:05

lwxted


1 Answers

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.

like image 194
Marco A. Avatar answered May 26 '26 01:05

Marco A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!