Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual method only works for base class pointers [duplicate]

Below is the perhaps most simple example of a virtual function in C++:

#include <iostream>

class A {
public:
    virtual void f() {
        std::cout << "A";
    }
};

class B : public A {
public:
    void f() {
        std::cout << "B";
    }
};


int main() {
    {
        // calls f() in derived class
        A* a = new B();
        a->f();
    }
    {
        // calls f() in base class
        A a = B();
        a.f();
    }
}

The output of this program is BA. I expected it to be BB, i.e. call the base class in any case. Why does using a base class pointer make a difference here? I didn't find the explanation in the standard.

like image 712
ludwig prager Avatar asked Feb 21 '26 20:02

ludwig prager


1 Answers

This is called slicing. A a = B(); creates a copy which is of type A. All information about its source being B is forgotten. The only way to exploit polymorphism is through references or pointers (or mechanisms that allow compile-time polymorphism, like templates or function overloading for example).

like image 75
BartoszKP Avatar answered Feb 24 '26 08:02

BartoszKP



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!