Virtual Functions and Polymorphism
Call the right derived-class method through a base-class pointer or reference.
Intermediate
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2.0));
for (const auto &s : shapes)
std::cout << s->area() << '\n'; // Circle::area is called
virtual functions are dispatched at run time through a vtable (one extra pointer per object). Mark overrides with override so the compiler catches signature mistakes. Compile-time polymorphism (overloading, templates) has no run-time cost.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.