Take these two classes for example (C++)
class B1 {
public:
};
class B2 {
public:
void f0 () {}
void f1 () {}
};
How much bigger would class B2 be in memory Vs B1
I feel like it’s one of two answers:
A single 4 byte int pointer on 32 bit systems PER method.
Or something similar to what happens with Virtual Method Tables http://en.wikipedia.org/wiki/Virtual_method_table
Where there would be one 4 byte int pointer that points to a table for each class so it can look up it’s methods, which would make sense, but I don’t know if this happens for non-virtual methods.
Thanks.
Edit : Thanks for all of the awesome and quick replies 🙂 (Also marked answer)
None.
Non-virtual methods don’t increase a class’s size.
As for
virtualmethods, only the first one added to a class will increase its size, all subsequent ones do not.The fact that it’s
inlineor not also doesn’t affect the class size.The reason for this is that extra memory is not needed. Just imagine if all instances of all classes held pointers to all methods in the class and all parent classes. That would be a huge waste of memory.
the compiler can simply generate code to call
B2::f0(). Thethispointer is passed as an under-the-hood parameter so that the method know on which instance of the class to operate.For a simple test: