kifcaliph
kifcaliph

Reputation: 321

C++ initialization of non constant static member variable?

I got a qualification error of the member variable 'objectCount'. The compiler also returns 'ISO C++ forbids in-class intialization of non-const static member'. This is the main class:

#include <iostream>
#include "Tree.h"
using namespace std;

int main()
{
    Tree oak;
    Tree elm;
    Tree pine;

    cout << "**********\noak: " << oak.getObjectCount()<< endl;
    cout << "**********\nelm: " << elm.getObjectCount()<< endl;
    cout << "**********\npine: " << pine.getObjectCount()<< endl;
}

This is the tree class which contains the non-const static objectCount:

#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED

class Tree
{
    private:
        static int objectCount;
    public:
        Tree()
        {
            objectCount++;
        }
        int getObjectCount() const
        {
            return objectCount;
        }
    int Tree::objectCount = 0;
}
#endif // TREE_H_INCLUDED

Upvotes: 10

Views: 14133

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361352

int Tree::objectCount = 0;

The above line should be outside the class, and in .cpp file, as shown below:

//Tree.cpp 
#include "Tree.h"

int Tree::objectCount = 0;

Upvotes: 5

Puppy
Puppy

Reputation: 146910

You need to define it outside the scope in a single C++ file, not in the header.

int Tree::objectCount = 0;
int main()
{
    Tree oak;
    Tree elm;
    Tree pine;

    cout << "**********\noak: " << oak.getObjectCount()<< endl;
    cout << "**********\nelm: " << elm.getObjectCount()<< endl;
    cout << "**********\npine: " << pine.getObjectCount()<< endl;
}

#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED

class Tree
{
    private:
        static int objectCount;
    public:
        Tree()
        {
            objectCount++;
        }
        int getObjectCount() const
        {
            return objectCount;
        }
}
#endif // TREE_H_INCLUDED

Upvotes: 3

Mahesh
Mahesh

Reputation: 34625

You have to define the static variable in the source file that includes this header.

#include "Tree.h"

int Tree::objectCount = 0;  // This definition should not be in the header file.
                            // Definition resides in another source file.
                            // In this case it is main.cpp 

Upvotes: 17

Related Questions