Search code examples
c++initializationstatic-members

How to declare and initialize a static member in a class?


When I compile code that includes the following header file I get an error message that says:

Graph.h:22: error: ISO C++ forbids in-class initialization of non-const 
static member `maxNumberOfNeighbors'

How can I declare and initialize a static member that is not const?

This is the .h file

#ifndef GRAPH_H
#define GRAPH_H

typedef char ElementType;
class Graph {
public:
    class Node {
    public:
        static int maxNumberOfNeighbors = 4;;
        int numberOfNeighbors;
        Node * neighbors;
        ElementType data;
        Node();
        Node(ElementType data);
        void addNeighbor(Node node);
    };

typedef Node* NodePtr;

Graph();
void addNode(Node node);
NodePtr getNeighbors(Node node);
bool hasCycle(Node parent);
private:
    NodePtr nodes;
    static int maxNumberOfNodes;
    int numberOfNodes;
};

#endif /* GRAPH_H */

Solution

  • One can definitely have class static members which are not CV-qualified (non const and not volatile). It is just that one should not initialize them (give them value) when one declare them inside the class, based on current ISO C++ regulations. In Comparison, it is OK to do so for non static data members(regardless of CV-qualification) Since C++11.

    Because static data members do not belong to any object, with the right access they can be assigned (and if they are not constant, they can be manipulated) outside of the class(keeping in mind the right scope operator). Also regardless of public/private declaration and CV-qualification, static data members can be initialized outside their class.

    So one way for initializing static data members, is to do so in the same block-scope/namespace where their classes(outer class in case of sub-classes) are situated, but not inside any class scope.

    For example:

    class Graph {
    public:
        class Node {
        public:
            static int maxNumberOfNeighbors;
           .
           .
           .
        };
    .
    .
    .
    };
    
    int Graph::Node::maxNumberOfNeighbors = 4;
    //also int Graph::Node::maxNumberOfNeighbors(4);
    
    
    

    Good luck!