Virtual function in C++

Level 4213 keystrokes

Calls draw through a Shape pointer that points to a Circle; because draw is virtual, Circle's version runs and Circle is printed.

C++ code

1class Shape {
2public:
// virtual: the function to run is chosen from the object's real type at run time
3 virtual void draw() { cout << "Shape" << endl; }
4};
5
// Circle derives from Shape
6class Circle : public Shape {
7public:
// override: the compiler checks that this really overrides a virtual function
8 void draw() override { cout << "Circle" << endl; }
9};
10
// A base-class pointer to a Circle created on the heap
11Shape* s = new Circle();
// Dynamic dispatch calls Circle::draw: prints Circle
12s->draw();
// Free the object (in real code, give Shape a virtual destructor when deleting through a base pointer)
13delete s;

Output

Circle
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 8
  • ;× 7
  • "× 4
  • (× 4
  • )× 4
  • {× 4
  • }× 4
  • :× 3
  • -× 1
  • *× 1

More C++ examples at level 4

← C++ typing practice