Declared with = 0, has no implementation in the base class — forces every derived class to provide its own implementation.
class Shape
{
public:
virtual double area() = 0; // pure virtual -- no body, no default behavior
};
// Shape s; // ERROR: cannot instantiate a class with a pure virtual function
class Circle : public Shape
{
double radius;
public:
Circle(double r) : radius(r) {}
double area() override { return 3.1416 * radius * radius; } // MUST implement, or Circle is abstract too
};
MCQ Trap: A pure virtual function (
= 0) has no base-class implementation and forces overriding; a plain virtual function has a default implementation that CAN be overridden but doesn't have to be.
class Shape
{
public:
virtual double area() = 0; // pure virtual -- the "= 0" is what makes it pure
};
// Shape s; // COMPILE ERROR: cannot declare variable of abstract type 'Shape'
class Circle : public Shape
{
double radius;
public:
Circle(double r) : radius(r) {}
double area() override { return 3.1416 * radius * radius; } // MUST provide this, or Circle stays abstract too
};
int main()
{
Circle c(5);
cout << c.area(); // OK -- Circle is concrete, all pure virtuals implemented
Shape* s = new Circle(5); // OK -- pointer/reference to abstract class is fine
return 0;
}
class Square : public Shape {}; // area() NOT implemented
// Square sq; // COMPILE ERROR -- Square is STILL abstract, since it didn't implement area()
A pure virtual function's "pureness" is inherited down the chain until some class actually implements it — students often assume any subclass automatically becomes concrete, which is false.
A regular virtual function has a default body, so a derived class may skip overriding it. A pure virtual function forces every concrete derived class to provide its own implementation — useful when there is no sensible default (e.g., Shape::area() — there's no meaningful "generic shape area").
virtual void f(); b) virtual void f() = 0; c) void f() {} d) static void f() = 0;= 0 syntax actually do to a virtual function?Square : public Shape doesn't implement area(), can you create a Square object? Why or why not?