In the chapter Polymorphism & Virtual Functions we wrote a base class Shape with a virtual function draw(), and every derived class gave its own version. Now suppose we also want every shape to report its area(). What should Shape::area() itself return? A "shape" in general has no area. There is no sensible formula. Returning 0 would be a lie, and printing an error at run time would be a bug waiting to happen.
C++ solves this with pure virtual functions and abstract classes. They let a base class say: "every shape must have an area(), but I am not going to provide one — each concrete shape will." The compiler then enforces that promise for you. This is how C++ implements the OOP idea of abstraction, and it is the C++ way of writing what other languages call interfaces.
Pure Virtual Functions
A pure virtual function is a virtual function declared with the pure-specifier
= 0. It says "derived classes must override this", and the base class usually provides no body for it.
The syntax is simply = 0 at the end of a virtual function declaration:
class Shape {
public:
virtual double area() const = 0; // pure virtual function
};The = 0 does not mean "returns zero" and has nothing to do with a null pointer. It is just the syntax the language chose for "pure". Read it as "no implementation here".
Abstract Classes
An abstract class is a class that has at least one pure virtual function (either declared in it, or inherited and not yet overridden). You cannot create objects of an abstract class; it can only be used as a base class.
A class that is not abstract — one whose every virtual function has a real implementation — is called a concrete class.
Unlike Java, C++ has no abstract keyword. A class becomes abstract automatically the moment it contains a pure virtual function.
A Complete Example
Here is the shapes program done properly:
#include <iostream>
#include <string>
class Shape {
public:
virtual double area() const = 0; // pure virtual
virtual std::string name() const = 0; // pure virtual
void describe() const { // normal member function
std::cout << name() << " with area " << area() << '\n';
}
virtual ~Shape() = default;
};
class Circle : public Shape {
double r;
public:
explicit Circle(double radius) : r(radius) {}
double area() const override { return 3.14159 * r * r; }
std::string name() const override { return "Circle"; }
};
class Rectangle : public Shape {
double w, h;
public:
Rectangle(double width, double height) : w(width), h(height) {}
double area() const override { return w * h; }
std::string name() const override { return "Rectangle"; }
};
void printArea(const Shape& s) { // works for ANY concrete shape
s.describe();
}
int main() {
Circle c(2.0);
Rectangle r(3.0, 4.5);
printArea(c);
printArea(r);
const Shape* shapes[] = { &c, &r };
double total = 0;
for (const Shape* s : shapes)
total += s->area();
std::cout << "Total area: " << total << '\n';
}Output:
Circle with area 12.5664
Rectangle with area 13.5
Total area: 26.0664Notice a few important things:
Shapedeclares what every shape can do (area(),name()), whileCircleandRectangledecide how.Shapealso has a normal function,describe(), that calls the pure virtual functions. This is perfectly fine: by the timedescribe()runs, the object is a realCircleorRectangle, so the virtual calls go to their overrides. This pattern — the base class writes the overall algorithm and derived classes fill in the steps — is called the Template Method design pattern.printArea()takes aconst Shape&. It works for every current and future shape without ever being modified.The abstract class has a virtual destructor. We will see why that matters below.
Rule 1: You Cannot Create an Object of an Abstract Class
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() = default;
};
int main() {
Shape s; // error
}GCC refuses, and helpfully tells you exactly which functions are still pure:
a2.cpp:8:11: error: cannot declare variable ‘s’ to be of abstract type ‘Shape’
8 | Shape s; // error
| ^
a2.cpp:1:7: note: because the following virtual functions are pure within ‘Shape’:
a2.cpp:3:20: note: ‘virtual double Shape::area() const’This is the whole point: if you could create a plain Shape, calling s.area() would have no function to run. The compiler stops the mistake at compile time instead of at run time.
For the same reason you also cannot:
write
new Shape,pass a
Shapeto a function by value or return one by value,make an array of
Shapeobjects (Shape arr[3];).
Rule 2: Pointers and References to an Abstract Class Are Fine
You cannot have a Shape object, but you can have a Shape* or a Shape& that refers to a concrete derived object. That is exactly how runtime polymorphism works.
#include <iostream>
#include <type_traits>
class Animal {
public:
virtual void sound() const = 0;
virtual ~Animal() = default;
};
class Dog : public Animal {
public:
void sound() const override { std::cout << "Woof\n"; }
};
int main() {
Dog d;
Animal* p = &d; // OK: pointer to abstract type
Animal& r = d; // OK: reference to abstract type
p->sound();
r.sound();
std::cout << std::boolalpha
<< std::is_abstract_v<Animal> << ' '
<< std::is_abstract_v<Dog> << '\n';
}Output:
Woof
Woof
true falseThe type trait std::is_abstract_v<T> (from <type_traits>, C++17; the older form std::is_abstract<T>::value is C++11) lets you check at compile time whether a class is abstract.
Rule 3: A Derived Class Must Override Every Pure Virtual Function
If a derived class overrides only some of the pure virtual functions, it is still abstract.
#include <iostream>
class Shape {
public:
virtual double area() const = 0;
virtual double perimeter() const = 0;
virtual ~Shape() = default;
};
class Square : public Shape {
double side;
public:
explicit Square(double s) : side(s) {}
double area() const override { return side * side; }
// perimeter() NOT overridden
};
int main() {
Square sq(2.0); // error
}a3.cpp:19:12: error: cannot declare variable ‘sq’ to be of abstract type ‘Square’
a3.cpp:10:7: note: because the following virtual functions are pure within ‘Square’:
a3.cpp:6:20: note: ‘virtual double Shape::perimeter() const’This is not always a mistake. Sometimes you want an intermediate abstract class. For example, Polygon might implement perimeter() (sum of sides) for all polygons but leave area() pure, and Triangle and Square then derive from Polygon. Only the leaf classes become concrete.
Using the override keyword (C++11) on every overriding function is strongly recommended: if you misspell the name or get the const wrong, you get a compile error instead of silently leaving the function pure.
What an Abstract Class Can Contain
Beginners sometimes think an abstract class may only contain pure virtual functions. That is not true. An abstract class is a normal class in every other way:
Member | Allowed in an abstract class? | Notes |
|---|---|---|
Data members | Yes | Shared state for all derived classes, e.g. a |
Constructors | Yes | Run when a derived object is created; often made |
Destructor | Yes | Should be |
Normal (non-virtual) functions | Yes | Like |
Virtual functions with a body | Yes | A default that derived classes may override |
Pure virtual functions | Yes (at least one) | What makes the class abstract |
Static members | Yes | Called as |
A constructor in an abstract class is useful even though nobody can create a Shape directly: when you create a Circle, the Shape part of it is constructed first, exactly as you learned in Inheritance.
A Pure Virtual Function Can Have a Body
This surprises many people, and it is a favourite interview question. A pure virtual function may have a definition. The class is still abstract, and derived classes must still override the function, but they can call the base version explicitly.
#include <iostream>
class Logger {
public:
virtual void log(const char* msg) = 0; // pure virtual...
virtual ~Logger() = default;
};
void Logger::log(const char* msg) { // ...with a default body
std::cout << "[default] " << msg << '\n';
}
class ConsoleLogger : public Logger {
public:
void log(const char* msg) override {
std::cout << "[console] ";
Logger::log(msg); // explicitly reuse the base body
}
};
int main() {
ConsoleLogger c;
Logger& l = c;
l.log("Server started");
}Output:
[console] [default] Server startedTwo rules:
The body must be written outside the class. Writing
virtual void log(const char*) = 0 { ... }inside the class is a syntax error.The base body is only reached through a qualified call like
Logger::log(msg). A normal virtual call always goes to the derived override.
Why do this? It gives a "default behaviour you must opt into". The base designer forces every derived class to think about log(), while still offering reusable code.
Pure Virtual Destructors
Sometimes you want a class to be abstract but there is no natural function to make pure. The trick is to make the destructor pure virtual. But there is a catch: a pure virtual destructor must still be defined.
#include <iostream>
class Base {
public:
virtual ~Base() = 0; // pure virtual destructor
};
Base::~Base() { // ...but it MUST still have a body
std::cout << "~Base\n";
}
class Derived : public Base {
public:
~Derived() override { std::cout << "~Derived\n"; }
};
int main() {
Base* p = new Derived;
delete p; // ~Derived runs first, then ~Base
}Output:
~Derived
~BaseWhy must it have a body? Because destructors are never "replaced" by derived ones. When a Derived object is destroyed, ~Derived() runs and then automatically calls ~Base(). If ~Base() has no body, there is nothing to call, and the linker complains:
a8.cpp:(.text._ZN7DerivedD2Ev[_ZN7DerivedD5Ev]+0x26): undefined reference to `Base::~Base()'
collect2: error: ld returned 1 exit statusAlways Give an Abstract Base a Virtual Destructor
Abstract classes are almost always used through base pointers. If you write Shape* p = new Circle(2); delete p; and Shape's destructor is not virtual, the behaviour is undefined (in practice, usually only ~Shape() runs and the Circle part is never cleaned up). The simple rule from the previous chapter applies doubly here:
If a class has any virtual function, give it a public virtual destructor —
virtual ~Shape() = default;is enough.
(The alternative recommended by the C++ Core Guidelines is a protected non-virtual destructor, which forbids deleting through a base pointer altogether. For beginners, public and virtual is the safe choice.)
Interfaces in C++
Java and C# have an interface keyword. C++ does not need one: an interface in C++ is just an abstract class that contains only pure virtual functions (plus a virtual destructor) and no data. Because C++ allows multiple inheritance, a class can implement several such interfaces.
#include <iostream>
#include <string>
#include <utility>
class Printable { // "interface": only pure virtuals
public:
virtual void print() const = 0;
virtual ~Printable() = default;
};
class Saveable { // another interface
public:
virtual bool save(const std::string& file) const = 0;
virtual ~Saveable() = default;
};
class Report : public Printable, public Saveable {
std::string title;
public:
explicit Report(std::string t) : title(std::move(t)) {}
void print() const override {
std::cout << "Report: " << title << '\n';
}
bool save(const std::string& file) const override {
std::cout << "Saving \"" << title << "\" to " << file << '\n';
return true;
}
};
void show(const Printable& p) { p.print(); }
void backup(const Saveable& s) { s.save("backup.txt"); }
int main() {
Report r("Sales Q3");
show(r);
backup(r);
}Output:
Report: Sales Q3
Saving "Sales Q3" to backup.txtThe function show() only knows about "things that can be printed" and backup() only knows about "things that can be saved". Neither depends on Report. This is the Dependency Inversion idea behind good design: code depends on small abstractions, not on concrete classes. Since the interfaces have no data members, the worst problems of multiple inheritance (duplicated data members, the diamond problem from Inheritance) largely disappear; the only thing each interface base adds to an object is its hidden vptr.
Abstract Class vs Interface vs Concrete Class
Feature | Concrete class | Abstract class | "Interface" (pure abstract class) |
|---|---|---|---|
Can create objects? | Yes | No | No |
Pure virtual functions | None | At least one | All functions (except the destructor, which still needs a body) |
Data members | Yes | Yes | No (by convention) |
Implemented functions | All | Some | None (by convention) |
Typical use | Real objects | Share code + force some overrides | Pure contract, often combined via multiple inheritance |
C++ vs Java Comparison
Concept | Java | C++ |
|---|---|---|
Abstract method |
|
|
Abstract class |
| Automatic if any pure virtual function exists |
Interface |
| Abstract class with only pure virtual functions |
Implementing many |
|
|
Abstract method with a body | Not allowed | Allowed (defined outside the class) |
A Dangerous Trap: Pure Virtual Calls in Constructors
While the Base part of an object is being constructed, the object is not yet a Derived. During construction (and destruction) of Base, virtual calls are resolved as if the object were just a Base. If such a call reaches a pure virtual function, the behaviour is undefined.
#include <iostream>
class Base {
public:
Base() { init(); } // calls a virtual function indirectly
void init() { setup(); }
virtual void setup() = 0;
virtual ~Base() = default;
};
class Derived : public Base {
public:
void setup() override { std::cout << "Derived::setup\n"; }
};
int main() {
Derived d; // undefined behavior!
}GCC compiles this without complaint because the virtual call is hidden inside init(). When run, a typical GCC/Linux build prints pure virtual method called and aborts the program — but since it is undefined behaviour, nothing is guaranteed. (If you call setup() directly in the constructor, GCC warns pure virtual ‘virtual void Base::setup()’ called from constructor, and because it then calls Base::setup directly, the link fails with an undefined reference unless that pure function happens to have a body.) The fix: never call virtual functions from constructors or destructors expecting derived behaviour; do the setup in the derived class or after construction.
Common Mistakes
Forgetting to override one pure virtual function, then wondering why the derived class "cannot be instantiated". Read the compiler's note: it lists the functions that are still pure.
Signature mismatch. Writing
double area()in the derived class when the base hasdouble area() constcreates a new function and leaves the pure one un-overridden. Useoverrideto catch this.Declaring a pure virtual destructor without defining it — linker error.
Missing virtual destructor in a polymorphic base — undefined behaviour when deleting through a base pointer.
Passing an abstract class by value: defining or calling
void f(Shape s)is a compile error (since C++20 a mere declaration is allowed, but it is useless). Useconst Shape&orShape*.Thinking
= 0means "returns 0". It only marks the function as pure.
Interview / GATE-Style Questions
Q1. What is the difference between a virtual function and a pure virtual function?
A virtual function has an implementation in the base class that derived classes may override. A pure virtual function (= 0) makes the class abstract and derived classes must override it to become concrete. A pure virtual function may still have a body defined outside the class, callable only with a qualified name.
Q2. Can an abstract class have a constructor? Why would it need one?
Yes. It cannot be called to create a standalone object, but it runs as part of constructing every derived object, initialising the base-class data members. Such constructors are often made protected.
Q3. Can we create a pointer to an abstract class? An array of abstract class objects?
A pointer (or reference) — yes, and that is how abstract classes are used. An array of objects — no, because that would require creating objects of the abstract type. An array of pointers (Shape* arr[3]) is fine.
Q4. Why must a pure virtual destructor have a definition?
Every derived class destructor implicitly calls the base class destructor after its own body finishes. If the base destructor has no definition, that call cannot be linked, giving an "undefined reference" linker error.
Q5. A class B derives from abstract class A but overrides only some of A's pure virtual functions. Is B abstract?
Yes. A class is abstract if it has at least one pure virtual function whose final overrider is still pure, whether declared in it or inherited. B stays abstract until all of them are overridden.
Q6. Can a derived class turn a normal virtual function back into a pure virtual one?
Yes. A derived class may override an inherited non-pure virtual function with virtual void f() override = 0;. The derived class then becomes abstract, even though its base was concrete. This is rare but legal.
Q7. What happens if a constructor (indirectly) calls a pure virtual function?
Undefined behaviour. During base construction the dynamic type is the base class, so the call resolves to the pure function. With GCC on Linux it typically prints "pure virtual method called" and aborts.
Summary
A pure virtual function is declared with
= 0; it says "derived classes must implement this".A class with at least one pure virtual function is an abstract class. You cannot create its objects, but you can use pointers and references to it.
A derived class is concrete only after it overrides every pure virtual function; use
overrideto avoid mistakes.Abstract classes can have data, constructors, normal functions and static members.
A pure virtual function can have a body (defined outside the class); a pure virtual destructor must have one.
An interface in C++ is an abstract class with only pure virtual functions and a virtual destructor.
Never call virtual functions from constructors/destructors expecting derived behaviour — calling a pure one is undefined behaviour.