C++: Why does a struct\class need a virtual method in order to be polymorphic?

Because the type of a polymorphic object in C++ is, basically, determined from the pointer to its vtable, which is the table of virtual functions. The vtable is, however, only created if there’s at least one virtual method. Why? Because in C++, you never get what you didn’t explicitly ask for. They call it “you don’t have to pay for something you don’t need”. Don’t need polymorphism? You just saved a vtable.

Leave a Comment