Roadmap to becoming a developer in 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1.0 KiB

Virtual Functions in C++

Virtual functions enable runtime polymorphism in C++, allowing derived classes to override base class behavior. When called via a base pointer/reference, the actual object's type determines which function is executed (dynamic dispatch). Non-virtual functions use compile-time resolution based on the pointer/reference type (static dispatch), which prevents overriding.

// Base class with virtual function
class Animal {
public:
    virtual void speak() { std::cout << "Generic sound"; }
};

// Derived class override
class Dog : public Animal {
public:
    void speak() override { std::cout << "Woof!"; } // Dynamic dispatch
};

Visit the following resources to learn more: