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

前端 未结 7 1116
孤城傲影
孤城傲影 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:05

    Because the class's functions are not saved inside the object itself. Think of it in terms of C programming, every function of class A takes one secret parameter, the this pointer, so in actuality they are just functions with one extra parameter.

    For example imagine it like this:

    int display(A* thisptr)
    {
       //do something
       printf("%d",thisptr->a); 
       return;
    }
    

    So the display function is saved as just a simple function with one extra parameter. The name though is mangled depending on the compiler.

    I believe that different rules apply for virtual functions which would involve function pointers but since I am not sure maybe someone else can enlighten us on this matter.

提交回复
热议问题