Skip to content

Virtual functions in C++ (added content) #8497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 18, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 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.

```cpp
// 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:

- [@official@C++ Virtual Functions Documentation](https://en.cppreference.com/w/cpp/language/virtual)
- [@article@GeeksforGeeks Virtual Functions Guide](https://www.geeksforgeeks.org/virtual-function-cpp/)
- [@video@Virtual Functions Explained (YouTube)](https://www.youtube.com/watch?v=oIV2KchSyGQ&ab_channel=TheCherno)