What is the difference between a virtual function and a pure virtual function?
Last updated
A virtual function provides a default implementation that derived classes may override; a pure virtual function (declared = 0) provides no implementation and forces derivation, making its class abstract.
Virtual function: Has a body; the base is fully instantiable and the derived class can optionally override it.
Pure virtual function:
Declared with
= 0; makes the class abstract so it cannot be instantiated directly.Any concrete derived class must override every pure virtual or it too stays abstract.
Note: A pure virtual can still have a definition you call explicitly, but the
= 0still forces overriding.
[lang:cpp]
struct Shape {
virtual double area() const = 0; // pure virtual -> abstract
virtual void draw() const { /*...*/ } // virtual with default
};
struct Circle : Shape {
double area() const override { return 3.14159 * r * r; }
double r;
};
- https://www.geeksforgeeks.org/cpp/difference-between-virtual-function-and-pure-virtual-function-in-c/
- https://www.geeksforgeeks.org/cpp/cpp-interview-questions/
- https://www.slainstitute.com/c-and-c-interview-questions-and-answers/
- https://www.hirist.tech/blog/top-20-c-oops-interview-questions-and-answers/
- https://codefinity.com/blog/Top-50-C-plus-plus-Interview-Questions-and-Answers