What is a pure virtual function and an abstract class in C++?

virtual void f() const = 0; is a pure virtual function. A class with at least one is an abstract class: you can not create an object of it, and the derived classes must implement the function.

struct Shape {
    virtual double area() const = 0;
};

int main() {
    Shape s;
}
Output

Abstract.cpp: In function 'int main()':
Abstract.cpp:6:11: error: cannot declare variable 's' to be of abstract type 'Shape'
6 | Shape s;
| ^
Abstract.cpp:1:8: note: because the following virtual functions are pure within 'Shape':
1 | struct Shape {
| ^~~~~
• 'virtual double Shape::area() const'
Abstract.cpp:2:20:
2 | virtual double area() const = 0;
| ^~~~

See Abstract Classes and Interfaces.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.