functions within a class

1
2
3
4
5
6
7
class A
{
  int a
public:
  get_a();
  set_a();
}


The sizeof(A) = 4 bytes.

Where are the functions stored in a class? Why does the sizeof(A) does not reflect with the memory of function definitions?
Because in C, the size of a structure is the sum of the sizes of the data members (plus padding), and structs could not have member functions.

In C++ the same rule therefore applies, except that virtual functions add additional overhead due to the vtable pointer(s).

(And before you try, you cannot do sizeof( A::get_a ) to try to determine the executable code size of the function.)
So where are the member functions stored? Obviously classes should have some knowledge about their locations.
member functions are not stored anywhere. their definitions are stored in the binary/executable. when you compile/link at that time the binding of the addresses takes place. so the calling function has the address thats it. taking your example:

1
2
3
4
5
6
7
8
9
class A
{
  int a
public:
  get_a() //definations are generated in binary, lets say it is stored at address
{}          //0x1000
  set_a() //lets say this is stored at address 0x2000
{}
};


void main()
{
A a; //here it will take 4bytes
now if you call any function then
the code flow has the address of the called function
a.set_a(); //this will bind to 0x2000 during compilation/linking
/**
when this code point is reached during binary execution,
code will start to execute from address 2000
actually these address are resolved when the binary is loaded in the memory.
i may not be very clear, hope you might get what im saying
*/
so function address doesnt needs to be stored in class object


}
study this and you will understand:

http://en.wikipedia.org/wiki/Call_stack
Topic archived. No new replies allowed.