Computer Algorithms II Lecture Notes

4 September 2008 • Dynamic Storage and C++


This code is broken for a number of reasons. First, the initialization should be

static const unsigned node_count;
node nodes[node_count];

with node_count being initialized somewhere outside the binary-tree class:

template <typename T>
static const unsigned binary_tree<T>::node_count = 10000;

But the code sill won't work for standards-compliant C++ compilers because the array-bounds isn't considered constant, despite what the code says. The easiest way around this problem is to replace the const declaration with a preprocessor macro:

#define node_count 10000

typedef <typename T>
class binary_tree {

  private:

    node nodes[node_count];
  };

Preprocessor macros are considered disreputable by some people (as you might expect, many of those people are the same ones that designed the static class-variable initialization syntax). This disdain has lead to the constant enum idiom:

enum { node_count = 1000 };
node nodes[node_count];

which, apart from being too clever by half, is standard C++. These are terrible work-arounds, but because we'll soon be discussing a better way around the problem, they'll stand for now.


This page last modified on 24 January 2006.