Diamond Inheritance in C++

Level 5540 keystrokes

Mammal and Bird both inherit virtually from Animal, so Bat contains only one Animal subobject. The most derived class Bat calls the Animal constructor itself, so "Animal" is printed once and name is unambiguous.

C++ code

// Common base class at the top of the diamond
1class Animal {
2protected:
3 string name;
4public:
// Prints when the Animal part is constructed
5 Animal(string n) : name(n) { cout << "Animal: " << name << endl; }
6};
7
// virtual inheritance: classes deriving from both share one Animal
8class Mammal : virtual public Animal {
9public:
// Animal(n) here is ignored when Mammal is part of a Bat
10 Mammal(string n) : Animal(n) { cout << "Mammal" << endl; }
11};
12
// Bird also inherits virtually from Animal
13class Bird : virtual public Animal {
14public:
15 Bird(string n) : Animal(n) { cout << "Bird" << endl; }
16};
17
// Bat inherits from both, closing the diamond
18class Bat : public Mammal, public Bird {
19public:
// The most derived class constructs the virtual base: Animal, then Mammal, Bird, Bat
20 Bat(string n) : Animal(n), Mammal(n), Bird(n) { cout << "Bat" << endl; }
// There is only one name, so this is not ambiguous
21 void identify() { cout << "I am " << name << endl; }
22};
23
// Prints Animal: Bruce, Mammal, Bird, Bat
24Bat b("Bruce");
// Prints "I am Bruce"
25b.identify();

Output

Animal: Bruce
Mammal
Bird
Bat
I am Bruce
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.

  • <× 24
  • :× 13
  • (× 13
  • )× 13
  • ;× 12
  • "× 12
  • {× 9
  • }× 9
  • ,× 3
  • .× 1

More C++ examples at level 5

← C++ typing practice