🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C++ Polymorphism — Complete Beginner Guide

C++ FundamentalsC++ Polymorphism — Virtual Functions and vtable🟢 Free Lesson

C++ Polymorphism — Complete Beginner Guide

Learning Objectives

  • Create polymorphic behavior with virtual functions
  • Call derived methods through base pointers
  • Explain the role of override clearly
  • Describe what a vtable does in simple terms

Many Shapes, One Interface

Polymorphism means one interface, many forms. A base class declares an action. Each derived class responds in its own way. Callers work with the base form and still get the correct specialized behavior.

A First Virtual Function

Mark a base method with the virtual keyword. Derived classes provide their own version.

#include <iostream>
#include <string>

class Shape {
public:
    virtual void draw() {
        std::cout << "drawing shape" << std::endl;
    }

    virtual ~Shape() = default;
};

class Circle : public Shape {
public:
    void draw() override {
        std::cout << "drawing circle" << std::endl;
    }
};

class Square : public Shape {
public:
    void draw() override {
        std::cout << "drawing square" << std::endl;
    }
};

The override keyword confirms that you intend to replace a virtual base method. If the signature drifts, the compiler warns you instead of silently creating a new function.

Calling Through a Base Pointer

Polymorphism shines when objects are handled through a base pointer or reference.

void render(Shape* s) {
    s->draw();
}

int main() {
    Circle c;
    Square q;

    render(&c); // prints circle line
    render(&q); // prints square line
    return 0;
}

The function does not know the concrete type, yet the correct draw runs. That is dynamic dispatch in action.

Call StyleTypical Dispatch
Object by valueOften static and slicing prone
Base pointerVirtual when method is virtual
Base referenceVirtual when method is virtual

Static Versus Dynamic Dispatch

Without virtual, the compiler binds the call at compile time based on the static type of the expression. With virtual, the final runtime type decides which function body runs. Use virtual when derived versions must be selected during execution.

What Is a vtable?

Each class with virtual functions has a hidden lookup table called a vtable. The table stores function pointers for the virtual methods of that class. Each object carries a hidden pointer to its class vtable, often called a vptr.

PieceRole
vtablePer class table of virtual method addresses
vptrPer object link to the correct table
dispatchRuntime reads the table and jumps to the right body

When Circle overrides draw, its vtable points to Circle draw. When Square overrides draw, its table points to Square draw. The call site only needs the object and the slot index, not the concrete type name.

This machinery costs a small amount of memory and an indirection per virtual call. In most application code that cost is negligible compared to the design flexibility.

The Slicing Trap

Assigning a derived object into a base object by value slices away the derived part. Virtual magic cannot recover what was never copied.

Circle c;
Shape s = c;   // slices to base part only
s.draw();      // may not call Circle version

Prefer pointers or references when you want polymorphic behavior.

Pure Virtual and Abstract Classes

A pure virtual function has no body in the base and forces children to implement it. A class with at least one pure virtual function becomes abstract and cannot be instantiated directly.

class Renderer {
public:
    virtual void render() = 0;
    virtual ~Renderer() = default;
};

class HtmlRenderer : public Renderer {
public:
    void render() override {
        std::cout << "html output" << std::endl;
    }
};

Abstract bases define contracts. Concrete children supply real work.

Override Destructors Carefully

Destruction through a base pointer requires a virtual base destructor. Without it, the wrong cleanup path may run. The earlier example used a defaulted virtual destructor for that reason.

Common Mistakes

MistakeResult
Forgetting virtual on baseWrong function runs
Missing override keywordSilent signature mismatches
Non virtual destructor plus delete through baseIncomplete cleanup risk
Slicing by valueDerived behavior lost
Marking everything virtualHarder reasoning and noise

A Polymorphic Demo

#include <iostream>
#include <string>

class Notification {
public:
    virtual std::string send() const {
        return "generic notice";
    }
    virtual ~Notification() = default;
};

class EmailNotice : public Notification {
public:
    std::string send() const override {
        return "email sent";
    }
};

class SmsNotice : public Notification {
public:
    std::string send() const override {
        return "sms sent";
    }
};

void dispatch(const Notification& n) {
    std::cout << n.send() << std::endl;
}

int main() {
    EmailNotice e;
    SmsNotice s;
    dispatch(e);
    dispatch(s);
    return 0;
}

One dispatch function supports every current and future notice type that follows the contract.

Key Takeaways

💡

  • virtual enables runtime selection of the right derived method
  • override documents intent and catches signature mistakes
  • Each polymorphic class keeps a vtable of function pointers
  • Prefer base pointers or references to avoid slicing
  • Give polymorphic bases virtual destructors

Practice Questions

  1. What problem does the virtual keyword solve compared with a normal method?
  2. In your own words, what does a vtable store?
  3. Why can slicing break polymorphic behavior?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C++ Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement