MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Object details

At this point you’re probably wondering the same thing that most C programmers do because C is a language that is very low-level and efficiency-oriented. A question that comes up a lot in seminars is “How big is an object, and what does it look like?” The answer is “Pretty much the same as you expect from a C struct.” In fact, a C struct.(with no C++ adornments) will usually look exactly the same in the code that the C and C++ compilers produce, which is reassuring to those C programmers who depend on the details of size and layout in their code, and for some reason directly access structure bytes instead of using identifiers, although depending on a particular size and layout of a structure is a nonportable activity.

The size of a struct is the combined size of all its members. Sometimes when a struct is laid out by the compiler, extra bytes are added to make the boundaries come out neatly – this may increase execution efficiency. In Chapters XX and XX, you’ll see how in some cases “secret” pointers are added to the structure, but you don’t need to worry about that right now.

You can determine the size of a struct using the sizeof operator. Here’s a small example:

//: C04:Sizeof.cpp
// Sizes of structs
#include <cstdio>
#include "Lib.h"
#include "Libcpp.h"
using namespace std;

struct A {
  int i[100];
};

struct B {
  void f();
};

void B::f() {}

int main() {
  printf("sizeof struct A = %d bytes\n",
         sizeof(A));
  printf("sizeof struct B = %d bytes\n",
         sizeof(B));
  printf("sizeof CStash in C = %d bytes\n",
         sizeof(CStash));
  printf("sizeof Stash in C++ = %d bytes\n",
         sizeof(Stash));
} ///:~ 

The first print statement produces 200 because each int occupies two bytes. struct B is something of an anomaly because it is a struct with no data members. In C, this is illegal, but in C++ we need the option of creating a struct whose sole task is to scope function names, so it is allowed. Still, the result produced by the second printf( ) statement is a somewhat surprising nonzero value. In early versions of the language, the size was zero, but an awkward situation arises when you create such objects: They have the same address as the object created directly after them, and so are not distinct. Thus, structures with no data members will always have some minimum nonzero size.

The last two sizeof statements show you that the size of the structure in C++ is the same as the size of the equivalent version in C. C++ endeavors not to add any overhead.

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru