Reputation: 1201
How exactly are the member functions in C++ represented in memory? I understand that there are basically three types of functions:
-Static: These are represented as any other global function
-Virtual: These can be accessed through the vtable, during run-time, in order to perform dynamic dispatch.
-Non-static and Non-virtual: I am in trouble here. Most articles, or explanations say, that they are just represented the same way as normal functions are in the code, the only difference is they expect a hidden "this" pointer as an argument, to be able to access the data of the instance. However, I am not quite sure how is this represented/implemented. For example, if I have:
class A:
int var_a;
public:
int get_member_var_a(){
return var_a;
}
A(int init): var_a(init) {}
A* instance_of_a = new A(4);
Now if I call
int tmp = instance_of_a->get_member_var_a();
Does the instance of the objet A
have a pointer to the function get_member_var_a
stored somewhere in the memory, and simply it calls the function, while passing an instance pointer as an extra argument?
Upvotes: 0
Views: 389
Reputation: 5387
The non-static non-virtual functions will be mangled into "new" functions by the C++ compiler. Also, the first parameter to the "new" functions will be the "this" pointer.
instance_of_a->get_member_var_a();
The compiler will convert the above line to something like:
mangled_function_name_for_get_member_var_a(this)
For example, the compiler may mangle the function to something like _ZN1A16get_member_var_aEv.
Upvotes: 1
Reputation: 12178
Your second assumption is probably true for most of implementations.
int A::get_member_var_a()
will most probably be compiled to something like
int __internal_compiler_prefix___A___get_member_var___thiscall(A* this)
all a->fun()
will be 'replaced' by compiler with fun(a)
.
storing address to function inside instance is just too big overhead (couple of bytes per method per object) and as such is even probably prohibited by standard.
Upvotes: 2