`virtual` — C++ Keyword

`virtual` — C++ Keyword

The virtual keyword in C++: enables runtime polymorphism through dynamic dispatch.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

virtual

Marks a member function for dynamic dispatch: when called through a pointer or reference to a base class, the most-derived override is invoked. A pure virtual function (= 0) makes the class abstract.

Syntax

virtual return-type function-name(params);
virtual return-type function-name(params) = 0;  // pure virtual
virtual ~ClassName();                            // virtual destructor

Example

#include <print>
#include <memory>
#include <vector>

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

struct Circle : Shape {
    double r;
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
};

struct Square : Shape {
    double s;
    explicit Square(double s) : s(s) {}
    double area() const override { return s * s; }
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(3.0));
    shapes.push_back(std::make_unique<Square>(4.0));

    for (const auto& sh : shapes) {
        std::println("{:.4f}", sh->area());   // dynamic dispatch
    }
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}