Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 439
kifcaliph Avatar asked Jul 16 '11 15:07

kifcaliph


People also ask

Where can a non-static reference member variable of a class be initialized?

Non-static data members may be initialized in one of two ways: 1) In the member initializer list of the constructor.

How do you initialize a static member?

We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.

Is a static data member it can only be initialized?

Static data members are declared inside the class but they are initialized outside of the class. Static member functions can be accessed using class name and scope resolution. Also, we can call the member function without creating any object of the class.

Why static variable initialized only once?

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once.


2 Answers

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 
like image 186
Mahesh Avatar answered Sep 28 '22 08:09

Mahesh


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;
like image 41
Nawaz Avatar answered Sep 28 '22 09:09

Nawaz