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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With