10

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 
1
  • There is another alternative that wasn't mentioned in any of the suggested answers at the time of this writing, which allows you to keep everything in a single header. See the example in this SO answer, it maps perfectly to your example. Commented Nov 9, 2015 at 21:53

3 Answers 3

17

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 
Sign up to request clarification or add additional context in comments.

4 Comments

there is still the following error 'two or more data types in declaration of objectCount'
I forgot to put this line int Tree::objectCount = 0; outside the class and I forgot to end the header class with semicolon thank you
Why does this variable have to be declared outside of the class? I am trying to define and initialize a private variable, and I am getting this same error. How do I do this outside the class?
@DavidFaux Show what are you trying to do. Only static const integral data members can be initialized within a class.
5
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; 

Comments

3

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.