Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the base class inherited twice even when one of them is inherited as virtual?

#include<iostream>
using namespace std;
int main(){
    class c1{
        public:
        int i;
    };
    class c2:virtual public c1{
        public:
            int j;
    };
    class c3:public c1{
        public:
            int k;
    };
    class c4:public c2,public c3{


    };

    c4 inst1;  //Its an error which indicates multiple base classes have beeen inherited
    inst1.i=34;     

}

My book says

the only difference between a normal base class and a virtual one is what occurs when an objects inherits the base more than once. If virtual base classes are used, then only one base class is present in the object. Otherwise, multiple copies will be found.

But in this program even when one of the base class is inherited as virtual why are there two copies?

like image 739
rimalroshan Avatar asked Nov 29 '25 06:11

rimalroshan


1 Answers

Inheriting virtually in one base class does not make all its sibling bases inherit virtually as well. Inheritance has to be marked virtual in all base classes that you would like to share, directly or indirectly, in the derived class.

Since you did not add virtual to c3, a C++ compiler cannot treat it inheriting c1 as virtual inheritance.

Adding virtual fixes this problem:

class c3 : virtual public c1{
public:
    int k;
}
like image 138
Sergey Kalinichenko Avatar answered Dec 01 '25 20:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!