There are so many questions about initializing static members in C++, and yet I couldn’t find this one.
class Node {
private:
static const int INITIAL_SIZE = 100;
static Node* node_space;
static int OUT_OF_BOUNDS = 0;
static Node BAD_NODE;
};
Node* Node::node_space = new Node[Node::INITIAL_SIZE];
This seems to work, but I also want to add BAD_NODE to this array as the first element.
Node Node::BAD_NODE = Node();
Node::node_space[OUT_OF_BOUNDS] = BAD_NODE;
The above doesn’t compile. The message is
Node.cpp:7: error: expected constructor, destructor, or type conversion before '=' token
This is for a school project in which we are implementing a linked list with an array.
What you may want to-do here, if you only have a single static data-object, but you want to dynamically initialize it, is to create a singleton object as a wrapper around your
Nodeclass. Basically what occurs with a singleton is you create a single version of a class that is initialized with a normal class constructor, but the constructor,operator=(), and copy-constructor are declaredprivate. Then a single static version of the class is created through a static variable, and there is a public accessor method that allows other portions of your code to access the singleton class (i.e., the accessor returns either a reference or constant reference to the static class you created).Now you would access your singleton via
Node_S::get_instance(). Since the copy and assignment operators are declaredprivate, you cannot create extra copies of your singleton … there will only be a single instance of this class created. If you needed to pass it around, you would do-so by reference. Furthermore there is no initialization ambiguity because all the static elements ofNodeare initialized in-order during run-time whenget_instance()is called. Sincesingleton_instanceis a static variable, the number of times the constructorNode_S()is run is only once, so you can basically place all your initialization code forNodesafely inside of the constructor. Then simply add any additional methods required to work with theNodetype in yourNode_Sinterface. So some common usage code might look like the following: