Why class size depend only on data members and not on member functions?

前端 未结 7 1094
孤城傲影
孤城傲影 2020-12-03 05:42

I want to know the detail description on the size of a class. I want to know if there is only data members & member function without any virtual keyword then why the cla

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 06:00

    This is implementation dependent - it's not specified in the standard. However, you are right, non-virtual member functions (and even virtual functions after the first one) don't affect class size.

    That's because it would use a lot of memory if every instance of the class would have pointers to all functions. And why would they? At runtime, the object knows what type it is, and it can call the appropriate function. And the same function is identical across instances, all that's different is the object it operates on, which is passed as a parameter under the hood.

提交回复
热议问题