Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

ERROR IN SIZE OF CLASS

Posted on 2001-06-08
11
Medium Priority
?
171 Views
Last Modified: 2010-04-02
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
Comment
Question by:mansukhdakhara
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 30

Expert Comment

by:Axter
ID: 6170309
This is a double post.  Please delete your other duplicate question.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6170311
>>? Use vc++ compiler for checking...
That's because of your project settings.

continue...
0
 
LVL 30

Expert Comment

by:Axter
ID: 6170315
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 30

Expert Comment

by:Axter
ID: 6170318
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
 
LVL 30

Accepted Solution

by:
Axter earned 300 total points
ID: 6170338
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
 
LVL 7

Expert Comment

by:KangaRoo
ID: 6170472
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
 
LVL 22

Expert Comment

by:nietod
ID: 6170714
>> 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
 
LVL 4

Expert Comment

by:prashant_n_mhatre
ID: 6171127
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
 
LVL 22

Expert Comment

by:nietod
ID: 6171284
>> 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
 
LVL 5

Expert Comment

by:BlackDiamond
ID: 6174037
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
 

Expert Comment

by:amp072397
ID: 6174879
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

598 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question