Labs ICT
๐ŸŽ“ SIWES/IT Login

Polymorphism

1 min read | C++ Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

Polymorphism

Polymorphism lets one interface work with different underlying types. In C++, this is achieved through virtual functions and overriding.

Virtual Functions

Declare a base class function as virtual to allow derived classes to override it. At runtime, the correct function is called based on the actual object type.

Override

Use the override keyword (C++11) in the derived class for clarity and safety.

#include <iostream>
using namespace std;

class Shape {
public:
  virtual double area() {
    return 0;
  }
};

class Circle : public Shape {
private:
  double radius;
public:
  Circle(double r) {
    radius = r;
  }

  double area() override {
    return 3.14159 * radius * radius;
  }
};

class Square : public Shape {
private:
  double side;
public:
  Square(double s) {
    side = s;
  }

  double area() override {
    return side * side;
  }
};

int main() {
  Shape* shapes[2];
  shapes[0] = new Circle(5);
  shapes[1] = new Square(4);

  for (int i = 0; i < 2; i++)
    cout << "Area: " << shapes[i]->area() << "\n";

  for (int i = 0; i < 2; i++)
    delete shapes[i];

  return 0;
}

๐Ÿงช Quick Quiz

What keyword makes a function virtual in C++?