Skip to content
Learn Netverks

Lesson

Step 15/36 42% through track

polymorphism-virtual

Polymorphism and virtual

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Polymorphism and virtual: the syntax, patterns, and safety habits you need before advancing in C++.

Virtual dispatch and vtables are classic interview topics—misuse causes performance and slicing bugs.

You will apply Polymorphism and virtual in contexts like: Game engines, trading systems, desktop apps, and performance-critical libraries.

Write C++ in main.cpp with int main(), click Run on server—the dev runner compiles with c++/g++ -std=c++17 -Wall and runs the binary; read template errors in stderr (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

virtual enables runtime polymorphism: calling the most-derived override through a base pointer or reference.

Virtual functions

class Shape {
public:
    virtual double area() const = 0;  // pure virtual
    virtual ~Shape() = default;
};

Pure virtual (= 0) makes the class abstract. Always give polymorphic bases a virtual destructor.

Important interview questions and answers

  1. Q: vtable cost?
    A: One pointer per object plus indirect call—acceptable for extensibility; avoid on hot inner loops if profiling shows issue.
  2. Q: override keyword?
    A: C++11 override catches signature mistakes at compile time.

Self-check

  1. Why virtual destructor on base classes?
  2. What makes a class abstract?

Tip: Always give polymorphic bases a virtual ~Base() = default;—otherwise deleting through base pointer leaks derived state.

Interview prep

Why virtual destructor?

Deleting a derived object through a base pointer requires the derived destructor to run.

Pure virtual (= 0)?

Makes the class abstract—derived classes must implement the function.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • vtable cost?
  • override keyword?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump