c++ - Size of a class with only one function which do not have body -


this question has answer here:

i have been asked question size of below give class:

class {  void abc(); } 

and if make function virtual size now

class {  virtual void abc(); } 

note: question in respect visual studio compiler.

i told first have 1 byte , second have 5 bytes compiler adds v pointer second.

i check on visual studio 2010 in 64 bit machine:-

the size of class in first case 1 byte , in second case 4 byte.i play around , found below results putting in questions:

  1. i found if class have functions in it(with body or without) , no data members, size of class 1 byte , object created have size 1 byte 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 case question member function not have size? , if so, how compiler identify them?

  1. as know, size of empty class 1 byte, if add data member suppose int has size 4 byte class should of 5 byte shows 4 byte. same in case of making function virtual add v pointer has size 4 byte, total size of class shows 4 byte. in case question if class has size of 1 byte , adding data member in it, final size should 1 byte+data member size?? or class size size of data members if present , 1 byte if don't?? , size of v pointers, 4 byte?

please let me know if not clear.

according c++ standard (9 classes)

4 complete objects , member subobjects of class type shall have nonzero size.109 [ note: class objects can assigned, passed arguments functions, , returned functions (except objects of classes 109) base class subobjects not constrained. copying or moving has been restricted; see 12.8). other plausible operators, such equality comparison, can defined user; see 13.5. —end note ]

so empty class shall have size. ms vc++ sets 1. when class has data member size size of data member including padding alignment. there no need add size of empty class size of added data members. important class had non-zero size.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -