Inheritance in C++
Level 4216 keystrokes
Dog inherits from Animal, so a Dog object can use the inherited name member and speak method as well as its own bark method.
C++ code
// Base class with a name and a speak method1class Animal {2public:3 string name; // Print the name followed by " speaks"4 void speak() { cout << name << " speaks" << endl; }5};6 // Dog derives publicly from Animal and inherits its public members7class Dog : public Animal {8public: // A method that only Dog has9 void bark() { cout << "Woof!" << endl; }10};11 12Dog d;// name is inherited from Animal13d.name = "Rex";// Inherited method: prints Rex speaks14d.speak();// Dog's own method: prints Woof!15d.bark();Output
Rex speaks Woof!
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.
<× 10;× 9"× 6(× 4)× 4{× 4}× 4:× 3.× 3!× 1