How does virtual inheritance and polymorphism work in C++, and why do base classes need virtual destructors?
Runtime polymorphism works through the virtual table. A class with virtual functions gets a hidden pointer to a table of function addresses; calling a virtual function through a base pointer looks up the derived implementation at runtime. The cost is one pointer per object, one indirection per call, and the loss of inlining.
Why the destructor must be virtual:
Base* p = new Derived();
delete p; // undefined behaviour if ~Base is not virtualWithout virtual, only ~Base runs. ~Derived never executes, so any resource the derived class owns leaks. The rule: any class intended to be inherited from and deleted polymorphically needs a virtual destructor. If a class is not meant to be a base, it does not need one — and adding it unnecessarily costs a vtable pointer.
Virtual inheritance solves the diamond problem. If B and C both inherit from A, and D inherits from both, D normally contains two copies of A — ambiguous and wasteful. Declaring class B : virtual public A makes them share one subobject.
Note: Use override on every overriding function. It makes the compiler verify that you are actually overriding something, catching the common bug where a signature differs slightly and you silently create a new function instead.





