Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the compiler store methods for C++ classes?

This is more a curiosity than anything else...

Suppose I have a C++ class Kitty as follows:

class Kitty
{
    void Meow()
    {
        //Do stuff
    }
}

Does the compiler place the code for Meow() in every instance of Kitty?

Obviously repeating the same code everywhere requires more memory. But on the other hand, branching to a relative location in nearby memory requires fewer assembly instructions than branching to an absolute location in memory on modern processors, so this is potentially faster.

I suppose this is an implementation detail, so different compilers may perform differently.

Keep in mind, I'm not considering static or virtual methods here.

like image 364
Mashmagar Avatar asked May 25 '10 19:05

Mashmagar


1 Answers

In the usual implementation, there's only one copy of any given function. The association between the code and the data for a given object instance is established by passing a hidden parameter (referred to a this in the function) that's a pointer to the object instance (and its data).

For virtual functions, things get a bit more convoluted: each class gets a vtable that holds a set of pointers to the virtual functions, and each object gets a pointer to the vtable for its class. The virtual functions are invoked by finding the vtable pointer, looking at the correct offset, and invoking the function pointed to by that pointer.

like image 80
Jerry Coffin Avatar answered Oct 03 '22 10:10

Jerry Coffin