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 Style | Typical Dispatch |
|---|---|
| Object by value | Often static and slicing prone |
| Base pointer | Virtual when method is virtual |
| Base reference | Virtual 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.
| Piece | Role |
|---|---|
| vtable | Per class table of virtual method addresses |
| vptr | Per object link to the correct table |
| dispatch | Runtime 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
| Mistake | Result |
|---|---|
| Forgetting virtual on base | Wrong function runs |
| Missing override keyword | Silent signature mismatches |
| Non virtual destructor plus delete through base | Incomplete cleanup risk |
| Slicing by value | Derived behavior lost |
| Marking everything virtual | Harder 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
- What problem does the virtual keyword solve compared with a normal method?
- In your own words, what does a vtable store?
- 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
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- 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
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- 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
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids 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