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

Object details

A question that comes up a lot in seminars is “How big is an object, and what does it look like?” The answer is “about what you expect from a C struct.” In fact, the code the C compiler produces for a C struct (with no C++ adornments) will usually look exactly the same as the code produced by a C++ compiler. This 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 (relying on a particular size and layout for a structure is a nonportable activity).

The size of a struct is the combined size of all its members. Sometimes when the compiler lays out a struct, it adds extra bytes 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 "CLib.h"
#include "CppLib.h"
#include <iostream>
using namespace std;

struct A {
  int i[100];
};

struct B {
  void f();
};

void B::f() {}

int main() {
  cout << "sizeof struct A = " << sizeof(A)
    << " bytes" << endl;
  cout << "sizeof struct B = " << sizeof(B)
    << " bytes" << endl;
  cout << "sizeof CStash in C = " 
    << sizeof(CStash) << " bytes" << endl;
  cout << "sizeof Stash in C++ = " 
    << sizeof(Stash) << " bytes" << endl;
} ///:~

On my machine (your results may vary) 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 print 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. One of the fundamental rules of objects is that each object must have a unique address, so 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++ tries not to add any unnecessary overhead.

Contents | Prev | Next


Contact: webmaster@codeguru.com
CodeGuru - the website for developers.
[an error occurred while processing this directive]