Memory allocation for member functions in C++

前端 未结 4 427
爱一瞬间的悲伤
爱一瞬间的悲伤 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).

    0 讨论(0)
  • 2020-12-09 20:07

    Non-virtual functions aren't part of the class's memory. The code for the function is baked into the executable (much like a static member), and memory is allocated for it's variables when it is called. The object only carries the data members.

    0 讨论(0)
  • 2020-12-09 20:13

    Size of any class depends upon the size of the variables in the class and not the functions. Functions are only allocated space on the stack when called and popped out when return.. So the size of a class is generally the sum of sizes of non static member variables...

    0 讨论(0)
  • 2020-12-09 20:15

    Non-virtual member functions do not need to be "allocated" anywhere; they can essentially be treated as normal non-class functions with an implicit first parameter of the class instance. They do not add to the class size normally.

    0 讨论(0)
提交回复
热议问题