The short answer
In object-oriented programming, an abstract class is a base class meant to be inherited from, not used to create objects directly. It can declare operations that subclasses must implement, and it can also include code that subclasses inherit unchanged.
How languages handle the idea
- Java and C# use an
abstractkeyword. They also have a separateinterfacekeyword for listing methods that a class must implement. - Python has the
abcmodule, which providesABCandabstractmethodfor the same purpose. - C++ has no
abstractkeyword. A class becomes abstract when it has at least one pure virtual function.
An example in C++
#include <iostream>
#include <string>
class Animal {
public:
virtual ~Animal() = default;
virtual std::string sound() const = 0; // Subclasses must provide this
std::string introduce() const {
return "This animal says " + sound();
}
};
class Dog : public Animal {
public:
std::string sound() const override { return "woof"; }
};
class Cat : public Animal {
public:
std::string sound() const override { return "meow"; }
};
int main() {
// Animal a; // Error: Animal is abstract
Dog rex;
Cat tom;
std::cout << rex.introduce() << "\n"; // This animal says woof
std::cout << tom.introduce() << "\n"; // This animal says meow
}
Animal can’t be created on its own, because sound() is pure virtual. introduce() is inherited unchanged by Dog and Cat. It calls sound(), and each subclass answers with its own sound.
Abstract and concrete classes
- An abstract class cannot be instantiated. In C++, it has at least one pure virtual function.
- A concrete class can be instantiated. Every pure virtual function it inherits has been overridden.
Building on inheritance
Abstract classes depend on inheritance in c, since a subclass must derive from the abstract class to fill in its functions. If the Animal example was hard to follow, read that topic first and then come back.
Why designers use them
- They define a contract that several classes must meet.
- They let code depend on the general type instead of each specific class.
- Depending on abstractions rather than concrete classes is one idea behind solid principles in c.
Abstract classes and interfaces
Abstract classes and interfaces overlap. An abstract class can hold data and ordinary functions, while an interface usually describes only what a class must provide. In C++, both are built from classes, so the difference is mostly one of design. For the C++ rules, see the c abstract class guide.