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
Non-static data members may be initialized in one of two ways: 1) In the member initializer list of the constructor.
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.
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.
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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With