Multiple Inheritance in C++
Level 5462 keystrokes
Document inherits from two abstract interfaces, Printable and Serializable, and implements the pure virtual function of each. It prints its content and then a JSON-like string.
C++ code
// Interface for objects that can be printed1class Printable {2public: // Pure virtual: every concrete subclass must implement print3 virtual void print() const = 0;4};5 // Interface for objects that can be turned into a string6class Serializable {7public: // Pure virtual function that returns the serialized form8 virtual string serialize() const = 0;9};10 // Multiple inheritance: Document derives from both interfaces11class Document : public Printable, public Serializable { // Private text of the document12 string content;13public:14 Document(string c) : content(c) {} // Implements Printable: prints the content15 void print() const override { cout << content << endl; } // Implements Serializable: \" puts double quotes inside the string16 string serialize() const override { return "{\"doc\":\"" + content + "\"}"; }17};18 19Document doc("Hello World");// Prints "Hello World"20doc.print();// Prints {"doc":"Hello World"}21cout << doc.serialize() << endl;Output
Hello World
{"doc":"Hello World"}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.
;× 11"× 10(× 9)× 9<× 8{× 7}× 7:× 6\× 4.× 2