The need for virtual inheritance
Solve data redundancy and ambiguity caused by diamond inheritance . Since both B and C inherit class A, then B and C each have a copy of A, and D inherits B and C respectively, then there are two copies of a in D, resulting in data redundancy, and in When accessing the _a member, there will be ambiguity, and the pointing is unclear. So in order to solve this problem, virtual inheritance was introduced
What is virtual inheritance
Virtual inheritance means that when B and C inherit A, adding the keyword virtual is virtual inheritance.
#include<iostream>
using namespace std;
class A{
public:
int _a;
};
class B :virtual public A{
public:
int _b;
};
class C :virtual public A{
public:
int _c;
};
class D :public B,public C{
public:
int _d;
};
int main(){
D d;
d._a=1;
d._b = 2;
d._c = 3;
d._d = 4;
cout<<sizeof(d)<<endl;// 20 //虚继承后大小变为24
system("pause");
return 0;
}
Why does the size of D become larger after virtual inheritance? Does this not solve the effect of data redundancy?
, according to the results, do you think that the problem of data redundancy has not been solved? This is because the data in A is small. If there are many members in A and the space is large, then the role of the two pointers is very large, you can A lot of space overhead is omitted.