What is an abstract class, and how do you create one in C++?
Last updated
An abstract class is one that cannot be instantiated on its own because it declares at least one pure virtual function; it exists to define a common interface that derived classes must complete.
How to create one: Declare at least one pure virtual function using
= 0, e.g.virtual void draw() = 0;.Rules:
You cannot create an object of it directly, but you can have pointers/references to it for polymorphism.
A derived class stays abstract until it overrides all inherited pure virtual functions.
It may still have constructors, data members, and even a definition for a pure virtual function (callable explicitly).
Always give it a
virtualdestructor since it is a polymorphic base.
[lang:cpp]
class Shape {
public:
virtual double area() const = 0; // pure virtual -> abstract
virtual ~Shape() = default;
};
// Shape s; // error: cannot instantiate abstract class
- https://learn.microsoft.com/en-us/cpp/cpp/abstract-classes-cpp?view=msvc-170
- https://dev.to/jyoti_jingar/virtual-functions-abstract-classes-and-interfaces-in-c-31k5
- https://www.interviewbit.com/low-level-design-interview-questions/
- https://www.interviewbit.com/design-patterns-interview-questions/
- https://www.educative.io/answers/what-is-a-cpp-abstract-class
- https://dev.to/madgan95/object-oriented-programming-for-interview-cb2
- https://dev.to/jemmyasjd/oops-interview-questions-53ji