codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ polymorphism

C++ polymorphism

Many forms through virtual functions.

Mark a base method virtual and override it. Calls through a base pointer then run the derived version.

Example code

#include <iostream>
using namespace std;
class Animal { public: virtual void sound() { cout << "..." << endl; } virtual ~Animal() {} };
class Dog : public Animal { public: void sound() override { cout << "Woof" << endl; } };
int main() {
  Animal *a = new Dog();
  a->sound();
  delete a;
  return 0;
}

Run this code in the online editor

← C++ inheritanceC++ templates →