tags:

views:

105

answers:

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

A: 

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.

Nick
A: 

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.

JoshD
+8  A: 

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

Naveen
Very nicely said.
JoshD
this also answers a nagging question i had re thread-safety - thanks
slashmais
@Martin York : The Standard does prohibit size 0 objects. C++03 [Section `9/3`] says `Complete objects and member subobjects of class type shall have nonzero size.`
Prasoon Saurav
A: 

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

Ram Bhat