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