Does sizeof() show C++ class overhead?
c++
Solution
It seems that classes in c++ have no overhead at all.
As long as a class doesn't have virtual functions, then, yes. What kind of overhead do you expect? A virtual-less class is merely a collection of variables, with a set of functions associated with the type.
class Foo {
int a;
int bar() const { return a*a; }
};
could be trivially replaced by
struct Foo {
int a;
}
int Foo_bar(Foo const *that) {
return (that->a) * (that->a);
}
If you compiled each of those snippets, you'd see, that the assembly code looks almost identitcal.
However if you add one single virtual function, the game changes dramatically.
Problem
``` #include <iostream> using namespace std; class Test { int a; public: int getA() { return a; } Test(): a(1){} Test(int i): a(i){} }; int main() { Test t1(100); cout << sizeof(t1) << " " << sizeof(1) << endl; // 4 4 return 0; } ``` It seems that classes in c++ have no overhead at all. t1 is of size 4 like an integer. If I add another int member to Test, it will increase its size to 8. I would have expected something that is bigger than 4 Is it true that classes have no overhead?