Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory layout of C++ object

As far as my understanding all the member functions will be created in separate memory when class definition and is common for all objects. And only the member variables are created individually for each object. But how member function is executed when called using object?

Where is the address for these member function will be stored?


class B{
    public:
    int a;
    void fun(){

    }
};

int main(){
    B b;
    std::cout<<sizeof(b)<<std::endl;
}

If I execute this program, I get the output as 4(which is for only member variable). But calling b.fun() calls its member function correctly. How it is calling without storing its address within the object? Where the member function address are stored?

Is there anything like class memory layout where these addresses will be stored?

like image 347
Elanchezian R Avatar asked Oct 26 '25 07:10

Elanchezian R


2 Answers

Non-virtual member functions are extremely like regular non-member functions, with the only difference between them being a pointer to the class instance passed as a very first argument upon invocation.

This is done automatically by compiler, so (in pseudo-code) your call b.fun() can be compiled into

B::Fun(&b);

Where B::Fun can be seen as a usual function. The address of this function does not have to stored in actual object (all objects of this class will use the same function), and thus size of the class does not include it.

like image 182
SergeyA Avatar answered Oct 29 '25 06:10

SergeyA


Is there anything like class memory layout where these addresses will be stored?

There is for functions declared virtual, yes. In this case, the addresses of said functions are stored in a table and looked up at runtime. This in turn allows your code to dispatch to the correct function depending on the object's type when the function is called.

Non-virtual functions do not work this way. They're stored in the same way as free (i.e. non-member) functions, with the function name prefixed by the name of the class. No storage space within the object itself is required.

In both cases, a hidden this pointer is passed to the called function. This is what 'connects' it to your object.

like image 44
Paul Sanders Avatar answered Oct 29 '25 05:10

Paul Sanders