TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 13 of 18 · Free

Abstract Classes & Interfaces in C++ – Pure Virtual Functions

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Write pure virtual functions and explain why an abstract class cannot be created
  • Build an interface and code against it with references
  • Give a base class a virtual destructor and know why it matters

Every railway ticket has a fare, but a sleeper fare and an AC fare are worked out differently. There is no such thing as a plain "ticket" with no class. In C++ you can write a base class that says "every ticket MUST have a fare" without saying how. That is an abstract class.

What is an abstract class in C++?

In Lesson 4 you used virtual functions so the right version runs through a base pointer. A pure virtual function goes one step further: it has no body at all. You write = 0 instead.

A class with at least one pure virtual function is abstract. You cannot create objects of it. It exists only to be a parent.

Every child class must override all the pure virtual functions, or it is abstract too. Try it: add a Square class with area() = side * side and put it in the list.

🧩 C++ — you can edit this code
Output
Area: 12.56
Area: 12

Can an abstract class have data and normal functions in C++?

Yes. An abstract class can have member variables, a constructor and ordinary functions. Only the parts that differ are left pure virtual. (using Ticket::Ticket; lets a child reuse the parent's constructor instead of writing its own.)

Here every ticket has a passenger and a distance, and the same print() function. Only fare() is different for each class of travel.

print() calls fare(). Because fare() is virtual, the child's version runs. The base class writes the steps once; the children fill in the gap. Try it: make AC fare Rs 3 per km and run again.

🧩 C++ — you can edit this code
Output
Riya, 500 km: Rs 500
Aman, 500 km: Rs 1100

How do you make an interface in C++?

C++ has no interface keyword like Java. An interface is simply a class with ONLY pure virtual functions and a virtual destructor. It has no data.

An interface is a promise: "anything that is Printable has a print() function". Classes that have nothing else in common can make the same promise.

A function can take const Printable& and work with every class that keeps the promise, even ones written later. A class may also implement several interfaces; you will see that in Lesson 15.

🧩 C++ — you can edit this code
Output
Report: Sara 88%
Report: Sara 88%
Receipt: Rs 1500 paid
Receipt: Rs 1500 paid

Why does an abstract base class need a virtual destructor?

You often create a child object with new and keep only a base pointer to it. Later you delete it through that base pointer.

If the base destructor is virtual, C++ runs the child's destructor first and then the base's, just like other virtual functions. If it is not virtual, the child part is never cleaned up properly, and the C++ standard says the result is undefined.

Rule: if a class has any virtual function, give it a virtual destructor. virtual ~Base() = default; is enough. Look at the output: both destructors run, child first.

🧩 C++ — you can edit this code
Output
SMS: fee due on 10th
SmsNotifier cleaned up
Notifier cleaned up

What does "program to an interface" mean in C++?

It means your main code talks only to the interface, never to the exact class. The class that does the real work can be swapped without changing that code.

Below, FeeReminder only knows about the Notifier interface. Today it uses SMS; tomorrow you could plug in email or a printed slip.

This makes code easier to test and to grow. Try it: write an EmailNotifier class and pass it to remindAll instead.

🧩 C++ — you can edit this code
Output
[SMS to Mr. Rao] School fee of Rs 1500 is due
[SMS to Mrs. Iyer] School fee of Rs 1500 is due

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. An abstract class still has a constructor. What does this print?

#include <iostream>
using namespace std;

class Base {
public:
    Base() { cout << "B"; }
    virtual void hello() const = 0;
    virtual ~Base() = default;
};

class Child : public Base {
public:
    Child() { cout << "C"; }
    void hello() const override { cout << "H"; }
};

int main() {
    Child c;
    c.hello();
    cout << "\n";
    return 0;
}

Question 2. What does this print?

#include <iostream>
using namespace std;

class Meal {
public:
    virtual int price() const = 0;
    virtual ~Meal() = default;
    void bill() const { cout << "Rs " << price() + 5 << "\n"; }
};

class Thali : public Meal {
public:
    int price() const override { return 80; }
};

int main() {
    Thali t;
    const Meal& m = t;
    m.bill();
    return 0;
}

Question 3. Calf does not override sound(). What happens?

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() const = 0;
    virtual ~Animal() = default;
};
class Cow : public Animal {
public:
    void sound() const override { cout << "Moo "; }
};
class Calf : public Cow {
};

int main() {
    Calf c;
    c.sound();
    cout << "\n";
    return 0;
}

🧩 Your challenge

Make a kirana shop bill. Write an abstract class Item with a name, a pure virtual double price() const and a normal print() that shows the name and price. LooseItem is sold by weight (kg × rate per kg). PackedItem has an MRP and a quantity. Put the items in a list of Item pointers and print each line and the total. Expected output: Rice: Rs 260 Sugar: Rs 45 Biscuits: Rs 60 Total: Rs 365

Expected output :
Rice: Rs 260
Sugar: Rs 45
Biscuits: Rs 60
Total: Rs 365
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

#include <iostream>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;
    virtual ~Shape() = default;
};

int main() {
    Shape s;
    cout << s.area() << "\n";
    return 0;
}

Line 11: error: variable type 'Shape' is an abstract class

✅ Right

#include <iostream>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;
    virtual ~Shape() = default;
};

class Square : public Shape {
public:
    double area() const override { return 4 * 4; }
};

int main() {
    Square s;
    cout << s.area() << "\n";
    return 0;
}

You cannot create an object of an abstract class: it has no body for area(). Create an object of a child class that overrides it.

❌ Wrong

#include <iostream>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;
    virtual ~Shape() = default;
};

class Circle : public Shape {
public:
    double area() { return 3.14 * 2 * 2; }
};

int main() {
    Circle c;
    cout << c.area() << "\n";
    return 0;
}

Line 16: error: variable type 'Circle' is an abstract class

✅ Right

#include <iostream>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;
    virtual ~Shape() = default;
};

class Circle : public Shape {
public:
    double area() const override { return 3.14 * 2 * 2; }
};

int main() {
    Circle c;
    cout << c.area() << "\n";
    return 0;
}

area() without const is a different function, so the pure one is still not overridden and Circle stays abstract. Copy the exact signature and add override so the compiler checks it.

❌ Wrong

#include <iostream>
using namespace std;

class Notifier {
public:
    virtual void send() const = 0;
};

class Sms : public Notifier {
public:
    ~Sms() { cout << "Sms cleaned up\n"; }
    void send() const override { cout << "SMS sent\n"; }
};

int main() {
    Notifier* n = new Sms();
    n->send();
    delete n;
    return 0;
}

Line 18: warning: delete called on 'Notifier' that is abstract but has non-virtual destructor [-Wdelete-abstract-non-virtual-dtor]

✅ Right

#include <iostream>
using namespace std;

class Notifier {
public:
    virtual void send() const = 0;
    virtual ~Notifier() = default;
};

class Sms : public Notifier {
public:
    ~Sms() override { cout << "Sms cleaned up\n"; }
    void send() const override { cout << "SMS sent\n"; }
};

int main() {
    Notifier* n = new Sms();
    n->send();
    delete n;
    return 0;
}

Deleting a child through a base pointer needs a virtual destructor in the base. Without it the child's destructor may never run (undefined behaviour).

📌 Remember

  • A pure virtual function has = 0 and no body.
  • A class with any pure virtual function is abstract: you cannot create its objects.
  • Child classes must override every pure virtual function (same signature) — use override.
  • An interface is a class with only pure virtual functions and a virtual destructor.
  • Give every base class with virtual functions a virtual destructor.
  • Code that uses only the interface works with any class that implements it.

Finished the quiz and the challenge?

Questions students ask

What is the difference between an abstract class and an interface in C++?

C++ has no separate interface keyword. An abstract class may have data and normal functions plus at least one pure virtual function. An "interface" is just an abstract class with only pure virtual functions and no data.

Can a pure virtual function have a body in C++?

Yes, surprisingly, you may define it outside the class, and a child can call it as Base::f(). The class is still abstract. Beginners rarely need this.

Can I make a pointer to an abstract class?

Yes. You cannot create an object of an abstract class, but pointers and references to it are fine and very common. They point to child objects.

Why use abstract classes at all?

They let you write code once against a common shape, such as "every ticket has a fare". New kinds of tickets can be added later without changing that code.