Sometimes the parent can't give a sensible default. What is the area of “a shape”? We don't know until we know which shape. Write = 0 to make the method pure virtual: it has no body, and every child must provide one:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Shape {
public:
virtual double area() const = 0; // pure virtual
virtual string name() const = 0;
virtual ~Shape() {}
};
class Square : public Shape {
double side;
public:
Square(double s) : side(s) {}
double area() const override { return side * side; }
string name() const override { return "Square"; }
};
class Circle : public Shape {
double r;
public:
Circle(double radius) : r(radius) {}
double area() const override { return 3.14159 * r * r; }
string name() const override { return "Circle"; }
};
int main() {
Square s(3);
Circle c(1);
vector<const Shape*> shapes = {&s, &c};
for (const Shape* sh : shapes) {
cout << sh->name() << ": " << sh->area() << "\n";
}
return 0;
}Output
Square: 9 Circle: 3.14159
A class with at least one pure virtual method is abstract. You can't make an object of it directly – it only exists to be inherited from:
class Shape {
public:
virtual double area() const = 0;
};
int main() {
Shape s;
return 0;
}Output (the program does not compile)
main.cpp:7:11: error: variable type 'Shape' is an abstract class
Shape s;
^
main.cpp:3:20: note: unimplemented pure virtual method 'area' in 'Shape'
virtual double area() const = 0;
^Remember: An abstract class is a contract: “anything that wants to be a Shape must be able to tell me its area and its name.” Code that uses shapes only needs to know the contract.
Tip: In other languages this idea is called an interface. In C++ an interface is just an abstract class whose methods are all pure virtual.