Why class size depend only on data members and not

2019-01-11 13:51发布

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 class size depends only on data members. For an eg:

class A {
    int a;
public:
    int display() { 
    cout << "A=" << a << endl;
   }
};

When I check the sizeof(A) i found that it is 4 byte. Why it is so? Why member function has no effect on the size of class A?

Thanks

标签: c++ class size
7条回答
我只想做你的唯一
2楼-- · 2019-01-11 14:31

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.

查看更多
登录 后发表回答