`virtual` — C++ Keyword
`virtual` — C++ Keyword
The virtual keyword in C++: enables runtime polymorphism through dynamic dispatch.
`virtual` — C++ Keyword
The virtual keyword in C++: enables runtime polymorphism through dynamic dispatch.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
virtualMarks 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.
virtual return-type function-name(params);
virtual return-type function-name(params) = 0; // pure virtual
virtual ~ClassName(); // virtual destructor
#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
}
}
virtual destructor in a polymorphic base class to avoid undefined behavior when deleting via base pointer.override and final provide compile-time safety for overrides.final to enable devirtualization.virtualint 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;
}