I have been asked a question that what will be the size of below give class:
class A
{
void abc();
}
and now if I make that function virtual what will be the size now
class A
{
virtual void abc();
}
Note: The question in respect to visual studio compiler.
I told that first will have the 1 byte and second will have 5 bytes as compiler adds a V pointer to the second.
I just check on visual studio 2010 in 64 bit machine:-
the size of class in first case is 1 byte and in second case 4 byte.I also do some play around and found below results which I am putting in questions:
I found that if a class only have functions in it(with body or without) and no data members, the size of class always 1 byte and the object created also have the size 1 byte as below example:
class MyClass { void abc(){int x=0;} int getDouble(int y){return y*2;} }; int main() { MyClass obj;; std::cout<<sizeof(MyClass )<<"\n"; std::cout<<sizeof(obj)<<"\n"; int x; std::cin>>x; }
output:
1 1
So in this case my question is member function do not have any size? and if so, how the compiler identify them?
- As I know, the size of empty class is 1 byte, but if we add a data member suppose int which has size 4 byte the class should be of 5 byte but it shows 4 byte. Same as in case of making only function to virtual that will add a v pointer which has size 4 byte, but total size of class shows 4 byte. So in this case my question is if a class itself has a size of 1 byte and we are adding any data member in it, so the final size should be 1 byte+data member size?? Or the class size will only be the size of all the data members if they present and 1 byte if they don't?? And what is the size of V pointers, is it 4 byte?
Please let me know if I am not clear.