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
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?