Virtual Functions in C++

Level 5305 keystrokes

Shape is an abstract class with a pure virtual area(). Circle overrides it, and calling area() through a Shape* runs Circle's version, printing 78.5397.

C++ code

// Abstract base class
1class Shape {
2public:
// = 0 makes area pure virtual, so Shape itself cannot be instantiated
3 virtual double area() const = 0;
// Virtual destructor, so delete through a Shape* destroys the derived object correctly
4 virtual ~Shape() = default;
5};
6
// Circle derives from Shape
7class Circle : public Shape {
// Private member (class members are private by default)
8 double radius;
9public:
// Constructor sets the radius
10 Circle(double r) : radius(r) {}
// override implements area: π × r²
11 double area() const override { return 3.14159 * radius * radius; }
12};
13
// A base-class pointer to a Circle created on the heap
14Shape* s = new Circle(5);
// Virtual call runs Circle::area: prints 78.5397 (cout shows 6 significant digits)
15cout << s->area() << endl;
// Frees the object; thanks to the virtual destructor, ~Circle runs too
16delete s;

Output

78.5397
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.

  • ;× 9
  • (× 7
  • )× 7
  • :× 4
  • {× 4
  • }× 4
  • <× 4
  • *× 3
  • =× 3
  • -× 1

More C++ examples at level 5

← C++ typing practice