C++中类继承虚基类对象的大小
原理
虚函数指针占内存的一个地址长度 32位则长度为4个字节 64位则长度为8个字节
1、当类初始化对象时,首先初始化基类,成员对象,最后当前类构造函数
2、如果基类中含有虚函数,基类构造时会初始化一个虚指针指向一个虚函数表
3、父类继承一个虚基类时,会复用基类的虚指针作为当前类的虚指针,并当前类中如果有基类虚函数的同名函数,则覆盖掉虚函数表中该函数的地址,使用当前类的函数地址。并且如果当前类含有基类不存在的虚函数,则向虚函数表中添加该虚函数地址
4、父类继承两个及以上的虚基类时,会复用所有虚基类的虚函数表,并且找到同名函数进行覆盖,并且将新的虚函数添加到第一个继承的基类的虚函数表中
1、基类有虚函数,派生类无虚函数
#include <iostream>
#include<vector>
#include<stack>
#include<algorithm>
#include<string>
#include<unordered_set>
using namespace std;
class A {
public:
A(int x = 0) {
cout << "A" << x << endl;
}
void printA() {
cout << "Hello A";
}
};
class B :public A{
public:
B(int x = 0) {
cout << "B" << x << endl;
}
virtual void printB() {
cout << "Hello B";
}
};
class C : public B{
public:
C() {
cout << "C" << endl;
}
void printC() {
cout << "Hello C";
}
};
int main()
{
A a;
B b;
C c;
cout << "size of a:" << sizeof(a) << endl;
cout << "size of b:" << sizeof(b) << endl;
cout << "size of c:" << sizeof(c) << endl;
return 0;
}
2、基类有虚函数,派生类有虚函数
#include <iostream>
#include<vector>
#include<stack>
#include<algorithm>
#include<string>
#include<unordered_set>
using namespace std;
class A {
public:
A(int x = 0) {
cout << "A" << x << endl;
}
virtual void printA() {
cout << "Hello A";
}
};
class B :public A{
public:
B(int x = 0) {
cout << "B" << x << endl;
}
virtual void printB() {
cout << "Hello B";
}
};
class C : public B{
public:
C() {
cout << "C" << endl;
}
void printC() {
cout << "Hello C";
}
};
int main()
{
A a;
B b;
C c;
cout << "size of a:" << sizeof(a) << endl;
cout << "size of b:" << sizeof(b) << endl;
cout << "size of c:" << sizeof(c) << endl;
return 0;
}
3、基类无虚函数,派生类无虚函数
空类:1个字节
4、基类无虚函数,派生类有虚函数
4或8个字节 一个指针的大小
5、两个基类都有虚函数,派生类无虚函数
#include <iostream>
#include<vector>
#include<stack>
#include<algorithm>
#include<string>
#include<unordered_set>
using namespace std;
class A {
public:
A(int x = 0) {
cout << "A" << x << endl;
}
virtual void printA() {
cout << "Hello A";
}
};
class B {
public:
B(int x = 0) {
cout << "B" << x << endl;
}
virtual void printB() {
cout << "Hello B";
}
};
class C : public B, public A {
public:
C() {
cout << "C" << endl;
}
void printC() {
cout << "Hello C";
}
};
int main()
{
A a;
B b;
C c;
cout << "size of a:" << sizeof(a) << endl;
cout << "size of b:" << sizeof(b) << endl;
cout << "size of c:" << sizeof(c) << endl;
return 0;
}
6、两个基类都有虚函数,派生类有虚函数
#include <iostream>
#include<vector>
#include<stack>
#include<algorithm>
#include<string>
#include<unordered_set>
using namespace std;
class A {
public:
A(int x = 0) {
cout << "A" << x << endl;
}
virtual void printA() {
cout << "Hello A";
}
};
class B {
public:
B(int x = 0) {
cout << "B" << x << endl;
}
virtual void printB() {
cout << "Hello B";
}
};
class C : public B, public A {
public:
C() {
cout << "C" << endl;
}
virtual void printC() {
cout << "Hello C";
}
};
int main()
{
A a;
B b;
C c;
cout << "size of a:" << sizeof(a) << endl;
cout << "size of b:" << sizeof(b) << endl;
cout << "size of c:" << sizeof(c) << endl;
return 0;
}
结果: