Do class methods increase the size of the class instances?

后端 未结 4 1190
鱼传尺愫
鱼传尺愫 2020-12-14 00:40

The question is pretty straight forward. For clarity, consider the example below:

// Note that none of the class have any data members
// Or if they do have          


        
4条回答
  •  醉话见心
    2020-12-14 01:21

    Strickly speaking, this is implementation dependent. But the number of methods should not change the size of class objects. For non-virtual methods, there is nothing inside the object memory that relates to method pointers. If you have virtual methods, then each object has a single pointer to a vtable. The vtable grows when you add more methods, but the pointer size stays the same.

    Further info: for non-virtual methods, the compiler tracks method pointers for each class. when you call a non-virtual method, the compiler passes a pointer to the method that points to the object, either as a hidden parameter, or on the stack. This is how a method 'knows' its object and has access the this pointer. For virtual methods, the method pointer is actually an index into the vtable, so the compiler passes this to the dereferenced entry in the vtable.

提交回复
热议问题