Polymorphism in C++: Types, Virtual Functions and Examples

Polymorphism in C++ is the ability of a single function, operator or object to behave differently depending on the context in which it is used. C++ supports two types: compile-time polymorphism, resolved before the program runs, and runtime polymorphism, resolved during execution using virtual functions and vtables. It is one of the four pillars of object-oriented programming (OOP).

  • C++ supports two types of polymorphism in C++: compile-time (static) and runtime (dynamic).
  • Compile-time polymorphism uses function overloading and operator overloading; the compiler picks the right version at build time.
  • Runtime polymorphism relies on virtual functions and the vtable mechanism to decide behaviour while the program runs.
  • C does not support OOP-style polymorphism natively, but experienced C programmers simulate it using function pointers.
  • Virtual functions are the core mechanism behind runtime polymorphism; forgetting the virtual keyword is one of the most common bugs in C++ codebases.

How Polymorphism Works in C++

The word polymorphism comes from the Greek words for “many forms.” In C++, it means you can write one interface and have multiple implementations behind it. A Shape class can have a draw() function, and every derived class, Circle, Rectangle, Triangle, can implement draw() differently without the calling code ever needing to know which shape it is dealing with.

This design pattern shows up constantly in real software. Game engines use it to call update() on every game object without caring whether it is a player, an enemy or a particle effect. Payment gateways use it to process transactions through different providers with a single interface. According to the Stack Overflow Developer Survey 2024, C++ remains one of the top 10 most-used languages globally, and OOP concepts like polymorphism in C++ are tested in virtually every C++ technical interview at Indian product companies like Flipkart, Paytm and Infosys. According to the JetBrains State of Developer Ecosystem 2024, 23% of professional developers use C++ regularly, with systems programming and game development as the top use cases. In India, NASSCOM’s 2024 Tech Talent Report notes that C and C++ proficiency remains a baseline requirement for over 40% of engineering roles at product-based companies.

If you are studying BSc Computer Science subjects and scope or preparing for MCA placements, polymorphism in C++ will appear in your OOP paper, your viva and your campus recruitment rounds. It is not optional theory.

The Polymorphism Definition in C++ (Formal)

Formally, polymorphism in C++ is a compile-time or runtime mechanism that allows a single entity (a function name, an operator or a pointer to a base class) to refer to objects or operations of different types, with the correct behaviour selected automatically. The C++ standard achieves this through name mangling at compile time and through vtables at runtime.

Types of Polymorphism in C++

Type Also Called Mechanism Resolved At Example
Compile-Time Polymorphism Static Polymorphism / Early Binding Function overloading, operator overloading, templates Compile time add(int, int) vs add(double, double)
Runtime Polymorphism Dynamic Polymorphism / Late Binding Virtual functions, vtable, base class pointers Runtime Base class pointer calling overridden draw()

Compile-Time Polymorphism in C++

Compile-time polymorphism in C++ is resolved by the compiler before the executable is even created. The two main tools are function overloading and operator overloading. Templates are a third mechanism, though they deserve their own deep-dive.

Function Overloading

Function overloading lets you define multiple functions with the same name but different parameter lists. The compiler looks at the argument types you pass and picks the right version. There is no ambiguity at runtime because the decision is baked into the binary.

Here is a simple polymorphism in C++ example using function overloading:


#include <iostream>
using namespace std;

int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
string add(string a, string b) { return a + b; }

int main() {
    cout << add(3, 4) << endl;          // 7
    cout << add(3.5, 2.1) << endl;      // 5.6
    cout << add("Hello, ", "World!") << endl; // Hello, World!
    return 0;
}

The compiler uses name mangling internally to create three distinct function symbols. You write one name; the compiler handles three implementations. That is compile-time polymorphism in C++ doing exactly what it promises.

Operator Overloading

Operator overloading extends the same idea to C++ operators. You can redefine what + means for your custom class. If you build a Vector2D class for a physics simulation, you can write v1 + v2 instead of an ugly addVectors(v1, v2) call.

A practical tip here: do not overload operators if the meaning is not obvious. Overloading + for a matrix class makes sense. Overloading * to mean “save to database” is the kind of thing that gets you removed from a team’s code review approval list permanently.

Templates

Templates let you write a single function or class that works with any data type. std::vector is the most famous example. Templates are evaluated at compile time, which makes them compile-time polymorphism in C++. They are central to C++ generic programming and are covered extensively in the C++ reference documentation at cppreference.com.

Runtime Polymorphism and Virtual Functions in C++

Runtime polymorphism in C++ is where the language gets genuinely powerful. The key ingredient is the virtual keyword. When you declare a function as virtual in a base class, C++ sets up a vtable (virtual function table) for that class. Every object of that class carries a hidden pointer to its vtable, and when you call a virtual function through a base class pointer, C++ looks up the correct implementation at runtime.

What Is a Virtual Function in C++?

A virtual function is a member function declared with the virtual keyword in a base class. It tells the compiler: do not decide which version of this function to call at compile time; wait until runtime and check the actual object type. Derived classes override the virtual function to provide their own behaviour.

Here is the canonical polymorphism in C++ example with virtual functions:


#include <iostream>
using namespace std;

class Shape {
public:
    virtual void draw() {
        cout << "Drawing a generic shape" << endl;
    }
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing a Circle" << endl;
    }
};

class Rectangle : public Shape {
public:
    void draw() override {
        cout << "Drawing a Rectangle" << endl;
    }
};

int main() {
    Shape* s1 = new Circle();
    Shape* s2 = new Rectangle();

    s1->draw();  // Drawing a Circle
    s2->draw();  // Drawing a Rectangle

    delete s1;
    delete s2;
    return 0;
}

Both s1 and s2 are pointers of type Shape*. Without virtual, both calls would print “Drawing a generic shape” because the compiler would bind to the base class at compile time. With virtual, the vtable kicks in and routes each call to the correct derived class implementation. That is late binding, and it is the heart of runtime polymorphism in C++.

The vtable Mechanism

The vtable is an internal array of function pointers maintained by the C++ compiler. Each class with at least one virtual function gets its own vtable. When a derived class overrides a virtual function, its vtable entry points to the derived version. Every object of a polymorphic class stores a hidden pointer (the vptr) to its class’s vtable. This adds one pointer’s worth of memory overhead per object, typically 8 bytes on a 64-bit system, which is worth knowing when you are building memory-sensitive embedded or IoT applications.

Pure Virtual Functions and Abstract Classes

A pure virtual function has no implementation in the base class. You declare it with = 0. Any class with at least one pure virtual function becomes an abstract class, and you cannot instantiate it directly. This is C++’s way of enforcing an interface contract: every concrete subclass must implement the function or it will not compile.


class Shape {
public:
    virtual void draw() = 0;  // Pure virtual
};

One common mistake beginners make: forgetting to declare the base class destructor as virtual. If you delete a derived object through a base class pointer and the destructor is not virtual, only the base class destructor runs. The derived class destructor is silently skipped, and you get a memory leak. The ISO C++ FAQ lists this as one of the most frequent sources of subtle bugs in C++ codebases. Always write virtual ~Shape() {} in any base class you intend to use polymorphically.

The override Keyword

C++11 introduced the override specifier. Writing void draw() override in the derived class tells the compiler to verify that you are actually overriding a virtual function from the base class. If you misspell the function name or get the signature wrong, the compiler throws an error instead of silently creating a new, unrelated function. Use override every single time. It costs nothing and catches real bugs.

Difference Between Compile-Time and Runtime Polymorphism in C++

The key difference between compile-time and runtime polymorphism in C++ is when the binding happens. Compile-time polymorphism binds the function call to its implementation during compilation, so there is zero runtime overhead. Runtime polymorphism defers that decision to execution time via the vtable, which adds a small but measurable indirection cost. For most application-layer software, that cost is negligible. For hard real-time embedded systems, it can matter, which is why C with function pointers is still used in those contexts.

What About C?

C does not support object-oriented programming natively. There are no classes, no inheritance and no virtual functions. So polymorphism in C, strictly speaking, does not exist as a built-in language feature.

That said, experienced C programmers simulate polymorphism using function pointers stored in structs. The Linux kernel does this extensively. You define a struct that contains function pointers, and different “implementations” populate those pointers differently. It is manual, verbose and error-prone compared to C++ virtual functions, but it works.


/* Simulating polymorphism in C with function pointers */
#include <stdio.h>

typedef struct Shape {
    void (*draw)(struct Shape*);
} Shape;

void drawCircle(Shape* s) { printf("Drawing Circle\n"); }
void drawRect(Shape* s)   { printf("Drawing Rectangle\n"); }

int main() {
    Shape circle = { drawCircle };
    Shape rect   = { drawRect };

    circle.draw(&circle);
    rect.draw(&rect);
    return 0;
}

This is exactly how C achieves late binding without language support. If you want to understand the foundations before writing C code yourself, check out our guide on how to write, compile and run a C program.

The contrast between C and C++ here is instructive. C gives you the raw mechanism (function pointers) and makes you manage everything manually. C++ wraps that same mechanism in a safe, compiler-enforced abstraction (virtual functions and vtables). This is exactly why C++ was created: to bring OOP discipline to systems programming without sacrificing performance.

According to the TIOBE Index for 2025, C ranks second and C++ ranks third among the most popular programming languages worldwide. Both remain dominant in systems programming, embedded development and competitive coding curricula at Indian engineering colleges. Understanding why C++ added virtual functions on top of what C already offered is a question that comes up in GATE CS preparation and in interviews at companies like TCS and HCL.

When to Use C vs C++ for Polymorphism

If you are writing a hardware driver or a real-time embedded system where every byte of overhead matters, C with function pointers is still a valid choice. If you are building application-layer software, a game engine, a compiler, a trading system or anything where maintainability counts, C++ virtual functions are the right tool. The vtable overhead is negligible for most applications, and the compiler-enforced correctness saves real debugging hours.

Choosing the right tools from the start matters enormously. Our guide on software development tools to learn first covers the broader ecosystem decisions every programmer faces early in their career.

Frequently Asked Questions

What is polymorphism in C++?

Polymorphism in C++ is the ability of a single function, operator or base class pointer to behave differently depending on the object or arguments it operates on. C++ supports compile-time polymorphism (resolved by the compiler) and runtime polymorphism (resolved during program execution using virtual functions and vtables).

What are the types of polymorphism in C++?

C++ has two types of polymorphism. Compile-time polymorphism in C++ includes function overloading, operator overloading and templates; the compiler selects the correct version before the program runs. Runtime polymorphism uses virtual functions and inheritance so that the correct function is chosen while the program executes, based on the actual object type.

What is a virtual function in C++?

A virtual function is a member function declared with the virtual keyword in a base class. It instructs the C++ compiler to use late binding: instead of deciding at compile time which function to call, C++ looks up the correct implementation at runtime through the vtable. Derived classes override the virtual function to provide their own specific behaviour.

What is the difference between compile-time and runtime polymorphism in C++?

Compile-time polymorphism in C++ is resolved by the compiler before the program runs, using function overloading, operator overloading or templates. Runtime polymorphism is resolved during execution using virtual functions and the vtable mechanism. Compile-time polymorphism has no runtime overhead; runtime polymorphism adds a small vtable lookup cost but enables far more flexible and extensible designs.

Does C support polymorphism?

C does not support polymorphism as a built-in language feature because it has no classes or inheritance. C programmers can simulate runtime polymorphism manually by storing function pointers inside structs, which is the technique used in large C codebases like the Linux kernel. It works, but it requires more boilerplate and offers none of C++’s compiler-level safety checks.

Can you give a C++ polymorphism example?

Yes. Declare a base class Shape with a virtual void draw() function. Create derived classes Circle and Rectangle that each override draw(). Assign new Circle() to a Shape* pointer and call draw(): C++ calls Circle::draw(), not Shape::draw(), because of the vtable lookup. That is runtime polymorphism in C++ in its simplest form.

Strong C++ fundamentals are the launchpad for everything else in software engineering. Once you are comfortable with polymorphism in C++, virtual functions and OOP design, you are ready to move into areas that genuinely pay well and matter in 2025 and beyond.

  1. Write and run the examples above this week. Do not just read the code; type it, compile it, break it deliberately (remove virtual and observe the output change), then fix it. Hands-on muscle memory is irreplaceable.
  2. Explore how these concepts apply to your career path. If you are considering a future in full-stack development or systems roles, read our comparison of full stack developer vs software developer to understand where C++ and OOP skills fit. If you are targeting higher studies, check the jobs and salary after MCA to see which roles value strong programming fundamentals most.
  3. Take your skills into cybersecurity, AI or blockchain. Polymorphism in C++ is not just an academic concept; it is used in malware analysis, secure coding and smart contract design. If you want to know which languages power blockchain development, read our guide on the best blockchain programming languages. If you are interested in how programming fundamentals connect to ethical hacking, explore the CEH v13 AI online course at 3.0 University. For the full range of industry-aligned certifications in Cybersecurity, AI, Blockchain and Web3, browse the complete 3.0 University online certification courses catalogue. These programmes are built for students and professionals who want practical skills, not just theory.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles