Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation for member functions in C++

Tags:

c++

#include<iostream>
using namespace std;
class A
{

};
class B
{
        public:
                void disp()
                {
                        cout<<" This is not virtual function.";
                }
};
class C
{
        public:
                virtual void disp()
                {
                        cout<<"This is virtual function.";
                }
};
int main()
{
        cout<<"class A"<<sizeof(A)<<endl;
        cout<<"class B"<<sizeof(B)<<endl;
        cout<<"class C"<<sizeof(C)<<endl;
        return 0;
}

sizeof class A and class B are both 1 byte only.What about the memory allocation for member function disp in B.

like image 611
Jagan Avatar asked Oct 08 '10 06:10

Jagan


People also ask

How are member functions stored in memory?

Normal member functions are stored in the . text section of your program. They do not take up extra memory per each instance, because a member function takes in a pointer to the class instance, rather than creating a whole new function for each instance.

How much memory is allocated to a function in C?

Syntax: ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.

How would you allocate space for member functions?

member functions are created and placed in the memory space only once when they are defined as a part of a class specification. Since all the objects belonging to that class use the same member functions, no separated space is allocated for member functions when the objects are created.

How is memory allocated to static data members and member functions?

Note: Memory for member functions and static data members is allocated per class and not per object. The class sample has no data member(except static count), but this does not mean no memory space will be allocated to the objects of Sample. In such cases, minimum memory is set aside for object.


1 Answers

For each instance of the class, memory is allocated to only its member variables i.e. each instance of the class doesn't get it's own copy of the member function. All instances share the same member function code. You can imagine it as compiler passing a hidden this pointer for each member function so that it operates on the correct object. In your case, since C++ standard explictly prohibits 0 sized objects, class A and class B have the minimum possible size of 1. In case of class C since there is a virtual function each instance of the class C will have a pointer to its v-table (this is compiler specific though). So the sizeof this class will be sizeof(pointer).

like image 146
Naveen Avatar answered Oct 04 '22 21:10

Naveen