Diamond Inheritance
virtual keyword on multiple base class creates one and only copy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#include <iostream> #include <memory> class RootOfAll { public: RootOfAll(){ std::cout << "RootOfAll" << std::endl; } ~RootOfAll(){ std::cout << "~RootOfAll" << std::endl; } }; // create one copy class MidLeft: virtual public RootOfAll{ public: MidLeft(){ std::cout << "MidLeft" << std::endl; } ~MidLeft(){ std::cout << "~MidLeft" << std::endl; } }; // create one copy class MidRight: virtual public RootOfAll{ public: MidRight(){ std::cout << "MidRight" << std::endl; } ~MidRight(){ std::cout << "~MidRight" << std::endl; } }; class TopClass: public MidLeft, public MidRight{ public: TopClass(){ std::cout << "TopClass" << std::endl; } ~TopClass(){ std::cout << "~TopClass" << std::endl; } }; int main() { // only shared pointers may use on abstract std::unique_ptr<TopClass> p { new TopClass{}}; return EXIT_SUCCESS; } |