[comp.lang.c] ?-tion on sizeof classes

dmg@ssc-vax.UUCP (David Geary) (06/17/89)

In article <2425@blake.acs.washington.edu>, Thomas Keffer writes:
+ On p. 54 of The Bible BS says
+ 
+ 	"It is not possible to compute the size of an
+ 	object of a structure type simply as the sum of its
+ 	members.  The reason for this is that many machines
+ 	require [certain objects to] be allocated on
+ 	architecture - dependent boundaries."
+ 
+ Aside from this cavaet, is there any other reason why the size of an
+ object might not be the sum of its members?  Suppose I was willing
+ to check for the alignment problem.  Could I then be assured that
+ the whole is the sum of its parts, or will there ever be a "hidden"
+ member, put in there by the compiler?
+ 

If a class has virtual functions, it will contain an extra member
which points to the classes "vtable".  I find that examining the
.c file generated by the C++ compiler is invaluable in understanding
what is going on with C++:

TESTIT.CXX:


class test_class			// Class with no virtual functions.
{
  private:    	int x;                  // Just something to stick in here.

  public:      void dummy() {}          // Ok, here's a member function.  
};

class another				// Class with virtual functions.
{
  private:	int x;			// Same as above class.

  public:   virtual void dummy() {}     // Note virtual keyword.
};

main(){}  // We just want to see what the .c file produces...



TESTIT.C:



/* << cfxx :-  1.2 Apollo.0 >> */
/* < testit.cxx */
void *_new(); void _delete(); void *_vec_new(); void _vec_delete();
void exit();


struct test_class {	/* sizeof test_class == 4 */

int _test_class_x ;
};

struct another {	/* sizeof another == 8 */

int _another_x ;

int (**_another__vptr )(/* void ...  */);
};
static void _another_dummy (/* struct another*  */);
static int (*another__vtbl[])() = {
(int(*)()) _another_dummy , 0};

int main (){  _entry (); { }
 exit ( 0 ); }

static void _another_dummy (this )
struct another *this ;

{ }

/* the end */

  Notice that sizeof test_class == 4, and sizeof another == 8.  The only
difference between the two classes is the fact that the member function
dummy is virtual in class another.


-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ David Geary, Boeing Aerospace, Seattle                 ~ 
~ "I wish I lived where it *only* rains 364 days a year" ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~