Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 23: Polymorphism and Virtual Func | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 23 of 45

·C++

Lesson 23: Polymorphism and Virtual Functions

12 min

Course progress51%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Virtual functions and dynamic dispatch
  • Pure virtual functions and abstract classes
  • Overriding rules and covariant return types
  • Virtual destructors importance

Polymorphism and Virtual Functions

Polymorphism enables a base‑class pointer or reference to invoke derived‑class behaviour at runtime. This is achieved through virtual functions and a hidden v‑table.


Example: Dynamic dispatch with Animal hierarchy

class Animal {
public:
    virtual void speak() const = 0; // pure virtual
    virtual ~Animal() = default;
};

class Dog : public Animal {
public:
    void speak() const override { std::cout << \"Woof!\
\"; }
};

class Cat : public Animal {
public:
    void speak() const override { std::cout << \"Meow!\
\"; }
};

int main() {
    std::vector<std::unique_ptr<Animal>> zoo;
    zoo.emplace_back(std::make_unique<Dog>());
    zoo.emplace_back(std::make_unique<Cat>());
    for (const auto& a : zoo) {
        a->speak(); // calls the correct derived implementation
    }
    return 0;
}

Key points:

  • A class with at least one virtual function gets a v‑table.
  • Destructors should be virtual when deleting through a base pointer.
  • final can prevent further overriding.

Tip: Prefer non‑virtual functions for performance‑critical code. Use override to catch mistakes.


<Alert type="warning">Calling a virtual function from a base class constructor or destructor does not dispatch to the derived implementation.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 22: InheritanceContinue to lesson 24Lesson 24: Abstract Classes and InterfacesBack to C++ Course curriculum