Loading lessons...
Pure Virtual Functions, Abstract Classes & Virtual Destructors
Pure Virtual Functions, Abstract Classes & Virtual Destructors
In the Shape example of Lesson 28, Shape::area() returned 0, a meaningless value: there is no sensible area for "a shape in general". C++ lets a base class declare a function without defining it, as a pure virtual function.
A class with such a function is abstract: it defines an interface for its derived classes but cannot itself be instantiated. This lesson also explains why base classes need virtual destructors.
1. Pure Virtual Functions
A pure virtual function is a virtual function that has no definition in the base class. It is declared by writing = 0 after its prototype:
It is a placeholder ("do-nothing" function) that says: every concrete derived class must provide this function.
2. Abstract Classes
A class that contains at least one pure virtual function is an abstract class.
- No objects of an abstract class can be created.
Shape s;is a compile-time error. - Pointers and references to it are allowed, and are how it is used:
Shape* p = new Circle(2);. - A derived class that does not override every pure virtual function is also abstract.
- A class that overrides all of them is a concrete class; its objects can be created.
- An abstract class can still have data members, constructors and ordinary (or virtual) functions with bodies.
An abstract class is used as a base for an interface: it states what derived classes must do, and each derived class decides how.
#include <iostream>
using namespace std;
class Shape { // abstract class
protected:
const char* label;
public:
Shape(const char* l) : label(l) {}
virtual double area() const = 0; // pure virtual
virtual double perimeter() const = 0; // pure virtual
void describe() const { // an ordinary function using them
cout << label << ": area = " << area() << ", perimeter = " << perimeter() << endl;
}
virtual ~Shape() {}
};
class Rectangle : public Shape { // concrete: overrides both
double l, w;
public:
Rectangle(double a, double b) : Shape("Rectangle"), l(a), w(b) {}
double area() const {
return l * w;
}
double perimeter() const {
return 2 * (l + w);
}
};
class Circle : public Shape { // concrete
double r;
public:
Circle(double radius) : Shape("Circle"), r(radius) {}
double area() const {
return 3.14159 * r * r;
}
double perimeter() const {
return 2 * 3.14159 * r;
}
};
int main() {
// Shape s("x"); // error: cannot instantiate an abstract class
Shape* list[2];
list[0] = new Rectangle(3, 4);
list[1] = new Circle(1);
for (int i = 0; i < 2; i++) {
list[i]->describe();
}
for (int i = 0; i < 2; i++) {
delete list[i];
}
return 0;
}Output:
Rectangle: area = 12, perimeter = 14
Circle: area = 3.14159, perimeter = 6.28318A derived class that stays abstract
class Polygon : public Shape { // overrides only perimeter()
public:
Polygon() : Shape("Polygon") {}
double perimeter() const {
return 0;
}
};
// Polygon p; // error: area() is still pure, so Polygon is abstract tooVirtual function vs pure virtual function
| Virtual function | Pure virtual function |
|---|---|
| has a definition (body) in the base class | has no definition in the base: = 0 |
| derived classes may override it | concrete derived classes must override it |
| the class can still be instantiated | the class becomes abstract |
| gives a default behaviour | only declares the interface |
Abstract class vs concrete class
| Abstract class | Concrete class |
|---|---|
| has at least one pure virtual function | has no pure virtual functions (all are defined) |
| cannot be instantiated | can be instantiated |
| used as a base class / interface | used to create objects |
example: Shape, Employee, Account | example: Circle, Manager, SavingsAccount |
3. A Realistic Example: Payroll
#include <iostream>
using namespace std;
class Employee { // abstract base
protected:
const char* name;
public:
Employee(const char* n) : name(n) {}
virtual double pay() const = 0; // each kind is paid differently
void payslip() const {
cout << name << " earns Rs " << pay() << endl;
}
virtual ~Employee() {}
};
class Salaried : public Employee {
double monthly;
public:
Salaried(const char* n, double m) : Employee(n), monthly(m) {}
double pay() const {
return monthly;
}
};
class Hourly : public Employee {
double rate;
int hours;
public:
Hourly(const char* n, double r, int h) : Employee(n), rate(r), hours(h) {}
double pay() const {
if (hours <= 160) {
return rate * hours;
}
return rate * 160 + rate * 1.5 * (hours - 160); // overtime
}
};
class Commission : public Employee {
double sales;
public:
Commission(const char* n, double s) : Employee(n), sales(s) {}
double pay() const {
return 10000 + 0.05 * sales;
}
};
int main() {
Employee* staff[3];
staff[0] = new Salaried("Anita", 55000);
staff[1] = new Hourly("Bala", 300, 170);
staff[2] = new Commission("Charu", 400000);
double total = 0;
for (int i = 0; i < 3; i++) {
staff[i]->payslip();
total = total + staff[i]->pay();
}
cout << "Total payroll: Rs " << total << endl;
for (int i = 0; i < 3; i++) {
delete staff[i];
}
return 0;
}Output:
Anita earns Rs 55000
Bala earns Rs 52500
Charu earns Rs 30000
Total payroll: Rs 1375004. Virtual Destructors
When a derived object is deleted through a base-class pointer, the destructor called depends on the pointer's type, exactly like any other function. If the base destructor is not virtual, only the base destructor runs: the derived destructor is skipped, so any memory the derived part owns leaks (formally, the behaviour is undefined).
Making the base destructor virtual fixes this: delete basePtr then runs the derived destructor first, then the base destructor, as it should.
#include <iostream>
using namespace std;
class BaseNV { // non-virtual destructor
public:
~BaseNV() {
cout << " BaseNV destructor" << endl;
}
};
class DerivedNV : public BaseNV {
int* data;
public:
DerivedNV() {
data = new int[100];
}
~DerivedNV() {
delete[] data;
cout << " DerivedNV destructor (frees memory)" << endl;
}
};
class BaseV { // virtual destructor
public:
virtual ~BaseV() {
cout << " BaseV destructor" << endl;
}
};
class DerivedV : public BaseV {
int* data;
public:
DerivedV() {
data = new int[100];
}
~DerivedV() {
delete[] data;
cout << " DerivedV destructor (frees memory)" << endl;
}
};
int main() {
cout << "delete through BaseNV*:" << endl;
BaseNV* p = new DerivedNV;
delete p; // only ~BaseNV runs: 400 bytes leak
cout << "delete through BaseV*:" << endl;
BaseV* q = new DerivedV;
delete q; // ~DerivedV, then ~BaseV
return 0;
}Output:
delete through BaseNV*:
BaseNV destructor
delete through BaseV*:
DerivedV destructor (frees memory)
BaseV destructorRule: any class that has virtual functions, or is meant to be used as a polymorphic base class, should have a virtual destructor. (GCC can warn about deleting through a non-virtual destructor; the first part of this program is deliberately wrong.)
Why constructors cannot be virtual
A virtual call needs the object's vptr to find the right function. The vptr is set by the constructor, so before the constructor runs there is no vptr to use.
Also, to create an object you must already know its exact type, so there is nothing to decide at run time. A destructor, however, is called on an existing object whose vptr is set, so it can be virtual.
Pure virtual destructor
A destructor can even be pure virtual, to make a class abstract when it has no other natural pure function. It must still be defined, because derived destructors always call it:
class AbstractBase {
public:
virtual ~AbstractBase() = 0; // makes the class abstract
};
AbstractBase::~AbstractBase() {} // but a body is still requiredKey points to remember
- Pure virtual function:
virtual void f() = 0;with no body in the base class. - A class with at least one pure virtual function is abstract: no objects, but pointers and references are fine.
- A derived class must override all pure virtual functions to become concrete.
- Deleting a derived object through a base pointer needs a virtual destructor, otherwise the derived destructor is skipped.
- Constructors cannot be virtual (no vptr yet); destructors can and should be in polymorphic bases.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is a pure virtual function? What is an abstract class? Explain with a program. (10 Marks)
- Write: both definitions, the five properties of abstract classes, the
Shape/Rectangle/Circleprogram, and the virtual vs pure virtual table. - Q2. What is a virtual destructor? Why is it needed? Write a program. (5 Marks)
- Write: the problem of deleting through a base pointer, and the
BaseNV/BaseVprogram with its output. - Q3. Why can a constructor not be virtual while a destructor can? (2.5 Marks)
- Q4. Differentiate between an abstract class and a concrete class. (2.5 Marks)
- Q5. Write a payroll program using an abstract
Employeeclass. (5 Marks)