Jagan
Jagan

Reputation: 4897

Memory allocation for member functions in 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.

Upvotes: 12

Views: 12572

Answers (4)

Naveen
Naveen

Reputation: 73503

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).

Upvotes: 27

Laz
Laz

Reputation: 6224

Size of any class depends upon the size of the variables in the class and not the functions. Functions are only allocated space on the stack when called and popped out when return.. So the size of a class is generally the sum of sizes of non static member variables...

Upvotes: 1

JoshD
JoshD

Reputation: 12824

Non-virtual functions aren't part of the class's memory. The code for the function is baked into the executable (much like a static member), and memory is allocated for it's variables when it is called. The object only carries the data members.

Upvotes: 0

Nick
Nick

Reputation: 6846

Non-virtual member functions do not need to be "allocated" anywhere; they can essentially be treated as normal non-class functions with an implicit first parameter of the class instance. They do not add to the class size normally.

Upvotes: 1

Related Questions