c++ - about Multiple inheritance and virtual inheritance -


i don't quite understand multiple inheritance , virtual inheritance. plz me. here little test:

class test1 {};  class test21 : public test1 {};  class test22 : public test1 {};  class test3 : public test21, public test22 {};  int main() {     test1  * t1 = new test3();     delete t1;      system("pause>nul");     return 0; } 

i got error: error 1 error c2594: 'initializing' : ambiguous conversions 'test3 *' 'test1 *'.
why?

then tried this:

class test1     {};      class test21 : virtual public test1     {};      class test22 : virtual public test1     {};      class test3 : public test21, public test22     {};      int main()     {         test1  * t1 = new test3();         delete t1;          system("pause>nul");         return 0;     } 

now got error: debug assertion failed!

can explain me multiple inheritance , virtual inheritance?

your first piece of code has exact problem virtual inheritance solves: have diamond in inheritance hierarchy. test21 , test22 both inherit test1, when inherit both of them, two versions of test1 in hierarchy, ambiguous 1 wish use.

the solution, in second sample: virtually inherit test1 single version.

however, code has undefined behaviour.

test1  * t1 = new test3(); delete t1; 

you delete derived instance through pointer base class without virtual destructor. means test3 object not correctly destroyed.

you should add virtual destructors classes:

virtual ~test1() = default; //c++11 virtual ~test1() {}; //prior version 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -