- #include <iostream>
- using namespace std;
- class Base
- {
- public:
- Base(void);
- virtual ~Base(void);
- void f() { cout << "f()" << endl; }
- private:
- int a;
- char *p;
- };
- class Derived:public Base
- {
- public:
- Derived(void);
- ~Derived(void);
- private:
- int b;
- };
- int main()
- {
- cout << "Base: "<< sizeof(Base) << endl;
- cout << "Derived: " << sizeof(Derived) << endl;
- int c;
- cin >> c;
- return 0;
- }
输出:Base=12 Derived=16
然后我们去掉Base类中的virtual关键字。
输出:Base=8 Deruved=12
所以,sizeof类对象的大小包括:
1.非静态数据成员的大小(不包括静态数据成员,静态数据成员是全局的所有对象共享这个成员,而sizeof是:编译时,编译器计算出的栈空间大小)
2.如果类中有虚函数(无论有多少虚函数),则包括一个虚指针的大小(4)
3.类可能的边界对齐(32位机器是4的整数倍)
但是当存在继承关系,而子类中存在member data的时候,因为需要保持base class subobject 在derivaed class 中的原样性,所以继承类的对象大小会相应增大。
- #include <iostream>
- using namespace std;
- class Concrete{
- private:
- int val;
- char c1;
- char c2;
- char c3;
- };
- class Concrete1{
- private:
- int val;
- char bit1;
- };
- class Concrete2 : public Concrete1{
- private:
- char bit2;
- };
- class Concrete3 : public Concrete2{
- private:
- char bit3;
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- Concrete obj1;
- Concrete3 obj3;
- cout << "Concrete obj " << sizeof(obj1) << endl;
- cout << "Concrete3 obj " << sizeof(obj3) << endl;
- return 0;
- }
Concrete3 obj = 16