C++ Gripes

In C++ it's harder to shoot yourself in the foot, but when you do, you blow off your whole leg.

-- Bjarne Stroustrup

Inheritance and Array Decaying

Inheritance is a basic (and seemingly unproblematic) concept of the C++ language. In certain situations, however, it breaks type safety in a very subtle and hard-to-detect way. One such situation is arrays.

struct base {
  int i;
};

struct derived : base {
  float f;
};

void foo(base array[], size_t n) {
  size_t i;

  for (i = 0; i < n; ++i) {
    array[i].i = 0;
  }
}

derived array[2];
foo(array, 2);

When foo tries to access objects behind array[0], it will overwrite undefined regions of previous objects, instead of the member variable i of the expected object. This is caused by the pointer arithmetic implied by array subscription assuming an object size of sizeof(base), instead of the correct sizeof(derived).

Last modified: 2008-01-13 (edit)
Powered by PAL: Podius · Apache · Linux