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 class1class Animal {// protected: accessible from derived classes, but not from outside2protected:3 string name;4public: // Constructor stores the name5 Animal(string n) : name(n) {} // Generic version of speak in the base class6 void speak() { cout << name << " makes a sound" << endl; }7};8 // Dog inherits publicly from Animal9class Dog : public Animal {10public: // Passes the name on to the Animal constructor11 Dog(string n) : Animal(n) {} // Redefines speak; not virtual, so it hides Animal::speak instead of overriding it12 void speak() { cout << name << " barks" << endl; }13};14 // Creates a Dog named Rex15Dog d("Rex");// Calls Dog::speak: prints "Rex barks"16d.speak();Output
Rex barks
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