What are abstract classes and interfaces in C++?
Why Interviewers Ask This
This tests whether you can apply C++ knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
An abstract class contains at least one pure virtual function (= 0) — it cannot be instantiated directly. Derived classes must implement all pure virtual functions to become concrete. class Shape { // Abstract class public: virtual double area() const = 0; // Pure virtual virtual double perimeter() const = 0; // Pure virtual virtual void draw() const { // Non-pure virtual -- has default impl std::cout << "Drawing a shape\n"; } virtual ~Shape() = default; // Virtual destructor! }; // Can't do: Shape s; // ERROR -- abstract class // Concrete subclass must implement all pure virtuals: class Circle : public Shape { double radius; public: Circle(double r) : radius(r) {} double area() const override { return 3.14159 * radius * radius; } double perimeter() const override { return 2 * 3.14159 * radius; } };. "Interface" in C++: C++ has no interface keyword (unlike Java). An interface is modeled as an abstract class with ONLY pure virtual functions and a virtual destructor: class Drawable { public: virtual void draw() const = 0; virtual ~Drawable() = default; }; class Serializable { public: virtual std::string serialize() const = 0; virtual void deserialize(const std::string& data) = 0; virtual ~Serializable() = default; }; // Multiple "interfaces": class Document : public Drawable, public Serializable { void draw() const override { /* ... */ } std::string serialize() const override { /* ... */ } void deserialize(const std::string& data) override { /* ... */ } };. Why virtual destructor: without it, deleting a derived object through a base pointer calls only the base destructor — resource leak. Shape* s = new Circle(5); delete s; // Calls ~Circle then ~Shape only if ~Shape is virtual.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a C++ codebase.