# C++ Virtual Inheritance
- In C++ inheritance, marking a function as virtual tells the compiler:
> “If this function is overridden in a derived class, and I'm calling it through a base class pointer or reference, then use the most derived version.”
- This enables dynamic dispatch (i.e., function calls are resolved at runtime instead of compile time).
## What ```virtual``` inheritance does in C++
- Without virtual
- Function calls resolved at **compile time**
- Base class version is always used
- No polymorphism
- Fast but limited
- With virtual
- Function calls resolved at **run time**
- Derived class version is used (if available)
- Enable polymorphism
- Slighly slower, more flexible
## Why ```virtual``` matters?
If without virtual
```c++
class Animal {
public:
void speak() {
std::cout << "Animal sound\n";
}
};
class Dog : public Animal {
public:
void speak() {
std::cout << "Woof!\n";
}
};
Animal* pet = new Dog();
pet->speak(); // Prints "Animal sound" ❌
```
Now adding virtual
```c++
class Animal {
public:
virtual void speak() {
std::cout << "Animal sound\n";
}
};
class Dog : public Animal {
public:
void speak() override {
std::cout << "Woof!\n";
}
};
Animal* pet = new Dog();
pet->speak(); // Prints "Woof!" ✅
```
With ```virtual```, the program decides at runtime which ```speak()``` function to use, based on the actual object type (Dog), not just the pointer type (Animal*)
## How does it work internally?
C++ creates a virtual table (vtable) behind the scenes:
- Each class with virtual functions has a vtable - a list of function pointers
- Each object with virtual functions has a hidden pointer to its class vtable
- When you call a virtual function, the program:
- Look up the vtable of the actual object
- Find the correct function to call
- Execute it