[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 173
  • Last Modified:

ERROR IN SIZE OF CLASS

In the below class X :-
//////////////////////////////////////////
class X
{
   private:
           int i;
           short s;
           float f;
           

}

void main()
{
  X x; // object of the class X  

  cout<< sizeof(x);
  cout<< sizeof(int) << sizeof(short)<<sizeof(float);
 
}
/////////////////////////////////////////////////
my question is that the sizeof the object of the class
and the sum of the individual variable doesnt match
why it is so ? Use vc++ compiler for checking...


0
mansukhdakhara
Asked:
mansukhdakhara
1 Solution
 
AxterCommented:
This is a double post.  Please delete your other duplicate question.
0
 
AxterCommented:
>>? Use vc++ compiler for checking...
That's because of your project settings.

continue...
0
 
AxterCommented:
Click on the Main menu "Project"
Then click "Settings"
Select the "C++" tab.
Change the catagory field to "Code Generation"
In the structure member field, that will state the byte settings for your structure.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
AxterCommented:
If you want your structure to show exactly the same size as it's members, you would have to set the above field to "1 Byte".

This could slow down your program, and make it less productive.
0
 
AxterCommented:
FYI,
This is not something that is unique to VC++.
Most compilers will compile to a minimum structor size, and most of them can be configured.
0
 
KangaRooCommented:
Modern day processors are happier if the data they fetch from memory is aligned to 4 or 8 byte boundaries, rather then on one byte. You class /might/ be represented internally as:

offset  size  member
00       4     i
04       2     s
06       2     Unused
08       4     f

adding up to 12 rather then 10 bytes. The compiler setting Axter decribes controls the alignment of classes and structures.
0
 
nietodCommented:
>> In the structure member field, that will state the byte
>> settings for your structure.
This changes the default settings that will be applied to all strucutres and classes.  But you can also use the pack #pragma to alter the packing setting from the default, this allows you to pack different structures and classes to different degrees.  i.e.

#pragma pack(push)    // Save current packing setting.
#pragma pack(1)    // Swithc to byte alignment.
class X
{
private:
   int i;
   short s;
float f;
}                        
#pragma pack(pop) // Restore the previous packing setting.

also note that even if you switch to byte allighment, there will be cases where the structure/class size is not the sum of the member sizes.  For example, if a class/structure has virtual functions it may contiain data used to help impliment this.  if th clas/structure has a base class/structure, it will store this too and may store other information as well.  
0
 
prashant_n_mhatreCommented:
KangaRoo has already mentioned this point. Let me elaborate.

Most CPUs require that objects and variables reside at particular offsets in the system's memory. For example, 32-bit processors require that a 4-byte integer reside at a memory address that is evenly divisible by four. This requirement is called "memory
alignment." On such architectures, a 4-byte int can be located at memory address 0x2000 or 0x2004, but not at 0x2001. On most UNIX systems, an attempt to use misaligned data results in a bus error, which terminates the program altogether. On Intel processors, the use of misaligned data is supported, but at a substantial performance
penalty. Therefore, most compilers automatically align data variables according to their type and the particular processor being used. This is why the size that structs and classes occupy may be larger than the sum of their members' size:

struct Employee
{
int ID;
char state[3]; /* CA, NY + null */
int salary;
};

Apparently, Employee should occupy 11 bytes (4+3+4). However, most compilers add an unused padding byte after the field "state" so that it aligns on a 4-byte boundary. Consequently, Employee occupies 12 bytes rather than 11. You can examine the actual size by using the expression sizeof(Employee).

0
 
nietodCommented:
>> On most UNIX systems, an attempt to use
>> misaligned data results
It has nothing to do with the OS, its dictated by the architecture of the CPU and its memory unit.

>> On Intel processors, the use of misaligned data is supported, but
>> at a substantial performance penalty.
At most 2 clock cycles per access.  For a 1 clock cycle instrctuion, that is a 200% slower, on the other hand, its only 2 more clock cycles which is trivial.  In addition, the penalty is often avoided because the CPU prefetches data.
0
 
BlackDiamondCommented:
I assume that you need to access the data without any offests included, hence this question.  Here is a quick workaround that will let you do that in this instance (I'll let use do the niceing of the class :->).  All of the data will be stored linearly in the unsigned character buffer "bytedata" which will be of the size that you specify.  If you need the memory to be accessed linearly, than use the pointer to that buffer.  If you want to reference by the type variables, then use the i, s, and f parameters (note that they are now pointers).  Hope this provides a little more insight...


class ByteData
{
   public:
      ByteData(size_t size) {
         bytedata = new unsigned char[size];
      }

      unsigned char * getByteData() {
         return bytedata;
      }
      void * getPtr (size_t offset) {
         return ((void *) (((unsigned long)bytedata) + offset));
      }
   private:
      unsigned char * bytedata;
};

class X
{
   public:
      X() {
         bytedata = new ByteData(sizeof(int) + sizeof(short) + sizeof (float));
         i = (int *)bytedata->getPtr(0);
         s = (short *)bytedata->getPtr(sizeof(int));
         f = (float *)bytedata->getPtr(sizeof(int) + sizeof(short));
      }
     

   private:
      ByteData * bytedata;
      int * i;
      short * s;
      float * f;
                   
};
0
 
amp072397Commented:
I deleted the duplicate post. Anyone can report duplicate posts at http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt, even if it is not your question. Thanks!

amp
Community Support Moderator
Experts Exchange
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now