Class Inheritance in C++

Level 5284 keystrokes

Dog inherits from Animal, uses its protected name and defines its own speak(). Because speak() is not virtual, Dog::speak hides Animal::speak rather than overriding it; calling it on a Dog object prints "Rex barks".

C++ code

// Base class
1class Animal {
// protected: accessible from derived classes, but not from outside
2protected:
3 string name;
4public:
// Constructor stores the name
5 Animal(string n) : name(n) {}
// Generic version of speak in the base class
6 void speak() { cout << name << " makes a sound" << endl; }
7};
8
// Dog inherits publicly from Animal
9class Dog : public Animal {
10public:
// Passes the name on to the Animal constructor
11 Dog(string n) : Animal(n) {}
// Redefines speak; not virtual, so it hides Animal::speak instead of overriding it
12 void speak() { cout << name << " barks" << endl; }
13};
14
// Creates a Dog named Rex
15Dog d("Rex");
// Calls Dog::speak: prints "Rex barks"
16d.speak();

Output

Rex barks
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.

  • <× 12
  • (× 8
  • )× 8
  • ;× 7
  • :× 6
  • "× 6
  • {× 6
  • }× 6
  • .× 1

More C++ examples at level 5

← C++ typing practice