Virtual Functions
Virtual Functions and Polymorphism
Polymorphism means "many forms" — the same call can behave differently depending on the actual type of the object. Virtual functions make this possible.
The Problem Without virtual
class Shape {
public:
string type() { return "shape"; }
};
class Circle : public Shape {
public:
string type() { return "circle"; }
};
void describe(Shape& s) {
cout << s.type() << endl;
}
Circle c;
describe(c); // prints "shape" — wrong!
Without virtual, the compiler picks the method at compile time based on the declared type (Shape&), not the actual type (Circle).
The Fix: virtual
Mark the base class method as virtual:
class Shape {
public:
virtual string type() { return "shape"; }
};
class Circle : public Shape {
public:
string type() override { return "circle"; }
};
Circle c;
describe(c); // prints "circle" — correct!
Now the method is selected at runtime based on the actual object type. This is runtime polymorphism.
override Keyword
The override keyword is placed after the parameter list in a derived class method. It tells the compiler you intend to override a virtual function from the base class. While not strictly required, it is strongly recommended because the compiler will produce an error if the method does not actually match a virtual function in the base — catching typos and signature mismatches at compile time:
class Circle : public Shape {
string type() override { return "circle"; } // OK: matches virtual in Shape
string tipe() override { ... } // error: no virtual tipe() in Shape
};
Pure Virtual Functions and Abstract Classes
A pure virtual function has no implementation in the base class — derived classes must provide one:
class Shape {
public:
virtual int area() = 0; // pure virtual
};
class Square : public Shape {
public:
int side;
Square(int s) : side(s) {}
int area() override { return side * side; }
};
// Shape s; // error: cannot instantiate abstract class
Your Task
Create a Shape base class with virtual string type() and virtual int area().
Create Rectangle (width, height) and Square (side) that override both methods.
Write a printInfo(Shape& s) function and call it with each shape.