Memory allocation for member functions in C++

前端 未结 4 428
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 19:47
#include
using namespace std;
class A
{

};
class B
{
        public:
                void disp()
                {
                        cout<&         


        
4条回答
  •  失恋的感觉
    2020-12-09 20:05

    For each instance of the class, memory is allocated to only its member variables i.e. each instance of the class doesn't get it's own copy of the member function. All instances share the same member function code. You can imagine it as compiler passing a hidden this pointer for each member function so that it operates on the correct object. In your case, since C++ standard explictly prohibits 0 sized objects, class A and class B have the minimum possible size of 1. In case of class C since there is a virtual function each instance of the class C will have a pointer to its v-table (this is compiler specific though). So the sizeof this class will be sizeof(pointer).

提交回复
热议问题