A class containing at least one pure virtual function — cannot be instantiated directly, only used as a base for derived classes.
class Shape // abstract -- has a pure virtual function
{
public:
virtual double area() = 0;
};
// Shape s; // ERROR
Shape* s = new Circle(5); // OK -- can still use it via a pointer to a CONCRETE derived class
An abstract class may still contain regular (non-pure) member functions with real implementations — it just needs at least one pure virtual function to qualify as abstract.
A class becomes abstract the moment it has even one pure virtual function — regardless of how many other fully-implemented methods it has.
class Shape
{
public:
virtual double area() = 0; // pure virtual -- makes Shape abstract
void printInfo() { cout << "A shape\n"; } // regular, fully implemented -- doesn't change the abstractness
};
// Shape s; // ERROR -- abstract, cannot instantiate
Shape* s = new Circle(5); // OK -- pointer to abstract class is fine, as long as Circle is concrete
An abstract class exists to say "every shape MUST have an area, but I won't say how" — it defines what derived classes must provide, without dictating how. This is the core idea behind interface-style design in C++.
class Shape
{
protected:
string color;
public:
Shape(string c) : color(c) {} // abstract classes CAN have constructors -- called by derived class constructors
virtual double area() = 0;
};
class Circle : public Shape
{
double radius;
public:
Circle(string c, double r) : Shape(c), radius(r) {} // must call Shape's constructor
double area() override { return 3.1416 * radius * radius; }
};
A common misconception: "abstract means no constructor." False — the constructor still runs (to initialize shared state like color), it just can never be called to create a Shape object directly, only as part of constructing a derived object.
Shape* s = new Circle(); is valid c) Only with static_cast d) Only in structsarea() unimplemented with an empty body?