Question on static int variable

  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    Static Variable
Click For Summary
The discussion centers around the initialization of a static member variable in a C++ class. A static member variable, such as `objectCount`, must be defined outside the class definition in the implementation file, which prevents multiple definitions when the header is included in different files. Attempting to initialize it directly in the class declaration results in a compilation error. The private access modifier restricts direct access from outside the class, but allows initialization in the implementation file. Understanding these rules is crucial for proper usage of static variables in C++.
yungman
Messages
5,741
Reaction score
294
I don't understand this header file in the book. In line 4, it declares static int objectCount;
I tried to put static int objectCount = 0; it won't compile, I tried putting in the next line objectCount = 0; it doesn't work. I tried putting in line 6, it doesn't work.

Being declare in private, obviously Tree::objectCount = 0 in main() won't work.
Then the book put that in line 11 OUTSIDE the Class definition, it works.

I don't understand any of this, can anyone explain to me. What is the statement in line 11 called?
C++:
class Tree
{
private: 
static int objectCount;//Static member variable      
public:
    //objectCount = 0;
    Tree() { objectCount++; }// Constructor
    int getobjectCount() const { return objectCount; }
};
#endif
int Tree::objectCount = 0;

Thanks
 
Technology news on Phys.org
yungman said:
I don't understand this header file in the book. In line 4, it declares static int objectCount;
I tried to put static int objectCount = 0; it won't compile, I tried putting in the next line objectCount = 0; it doesn't work. I tried putting in line 6, it doesn't work.

Being declare in private, obviously Tree::eek:bjectCount = 0 in main() won't work.
Then the book put that in line 11 OUTSIDE the Class definition, it works.

I don't understand any of this, can anyone explain to me. What is the statement in line 11 called?
C++:
class Tree
{
private:
static int objectCount;//Static member variable
public:
    //objectCount = 0;
    Tree() { objectCount++; }// Constructor
    int getobjectCount() const { return objectCount; }
};
#endif
int Tree::objectCount = 0;

Thanks
A static member variable is shared among all instances/objects of a class, and exists independently of those instances. C++ has a rule that says you can only define something once and because of some complicated issues that I won't try to explain, it means that non const static member variables need to be initialized in the cpp file, which is a single computational unit (otherwise if it's in the header, it would be like the one variable is being set multiple times, like if the header was included in multiple files).
C++:
class Tree
{
private:
static int objectCount;//Static member variable
public:
    Tree() { objectCount++; }// Constructor
    int getobjectCount() const { return objectCount; }
};
#endif
In the cpp file
C++:
int Tree::objectCount = 0;

Alternatively, you could not use a static variable. I don't think it's a great idea. What if you wanted to have multiple different trees? You would have both trees sharing the same count, which wouldn't work.

The better way to make a tree is make a Tree class and a TreeNode class like in this pseudocode.

C++:
class Tree
    int nodeCount;
    struct TreeNode {
        ...
    };
    int nodeCount
    TreeNode root;
#endif

There is one use case for static non-const member variables that I've needed sort of. Which is for giving each object a unique numerical id. In that case, the static variable holds the next id to assign. Each time an object is constructed it gets the next id and the next id is incremented.
 
Last edited:
  • Like
Likes yungman
Jarvis323 said:
A static member variable is shared among all instances/objects of a class, and exists independently of those instances. C++ has a rule that says you can only define something once and because of some complicated issues that I won't try to explain, it means that non const static member variables need to be initialized in the cpp file, which is a single computational unit (otherwise if it's in the header, it would be like the one variable is being set multiple times, like if the header was included in multiple files).
C++:
class Tree
{
private:
static int objectCount;//Static member variable
public:
    Tree() { objectCount++; }// Constructor
    int getobjectCount() const { return objectCount; }
};
#endif
In the cpp file
C++:
int Tree::objectCount = 0;

Alternatively, you could not use a static variable. I don't think it's a great idea. What if you wanted to have multiple different trees? You would have both trees sharing the same count, which wouldn't work.

The better way to make a tree is make a Tree class and a TreeNode class like in this pseudocode.

C++:
class Tree
    int nodeCount;
    struct TreeNode {
        ...
    };
    int nodeCount
    TreeNode root;
#endif

Thanks for the reply, what I don't understand is compiler flag me error when I do this:
C++:
class Tree
{  private:    static int objectCount = 0;
.
.}
I defined it the first time in one statement. Still it won't work.

I did not realize you can define Tree:ObjectCount = 0; outside the header file after it is declared private. This is why it's so confusing. It's almost like they make up their own rules on-the-fly.

So even if the variable is declared private, I can write Tree:ObjectCount = 0 in Implementation file? Then how come I cannot do it in main()? Now we are going in circle.....Private supposed to mean nobody can change it outside of header file, BUT you can change it in .cpp (Implementation) file...BUT you cannot change it in source.cpp file! I am missing something here.

ThanksHow come I get that funny thing every time I type o?
 
Last edited by a moderator:
yungman said:
Thanks for the reply, what I don't understand is compiler flag me error when I do this:
C++:
class Tree
{  private:    static int objectCount = 0;
.
.}
I defined it the first time in one statement. Still it won't work.

I did not realize you can define Tree:ObjectCount = 0; outside the header file after it is declared private. This is why it's so confusing. It's almost like they make up their own rules on-the-fly.

So even if the variable is declared private, I can write Tree:ObjectCount = 0 in Implementation file? Then how come I cannot do it in main()? Now we are going in circle.....Private supposed to mean nobody can change it outside of header file, BUT you can change it in .cpp (Implementation) file...BUT you cannot change it in source.cpp file! I am missing something here.

Thanks
It has nothing to do with private. It's a special case for static member variables. You can't assign it in the header file, so that's why you get a compiler error.

And the rule makes sense. Actually no member variables (except static const) can be assigned outside of the member functions. The constructor is for initialization. But the constructor is called for each object. So you would have the same variable being initialized multiple times, which doesn't make sense. They could have made it work, but they have a sort of strict mindset to make everything be logically sound on the surface.
 
Last edited by a moderator:
  • Like
Likes yungman
Jarvis323 said:
It has nothing to do with private. It's a special case for static member variables. You can't assign it in the header file, so that's why you get a compiler error.
So if there is any static variable, I have to assign in Implementation file. OK, I'll write it down in the notes.

I know about not to use static variable if possible, this is in Chapter 14 on Static Member and Instance Member. I have no choice but to study through it. Life is hard already, why set up more booby traps to fail?

Thanks for you time.
 
Static variables are defined for the class itself not for the instances created by the class. Where they come in handy is when you have some common variable for all instances like a global in non C++ C code.

I‘ve used it to keep a count of instances as they are created and destroyed. I’ve also used it for common constants across all instances of a class.

here’s some more info online

https://www.tutorialspoint.com/cplusplus/cpp_static_members.htm
 
  • Like
Likes jim mcnamara, Jarvis323 and yungman
yungman said:
So if there is any static variable, I have to assign in Implementation file. OK, I'll write it down in the notes.

I know about not to use static variable if possible, this is in Chapter 14 on Static Member and Instance Member. I have no choice but to study through it. Life is hard already, why set up more booby traps to fail?

Thanks for you time.
Yeah.

It has some use cases. Like I said, I used static member variables sometimes. You have to think if you actually need a single variable shared amongst all instances of a class or not, and realize the consequences of it.
 
  • Like
Likes yungman
yungman said:
How come I get that funny thing every time I type o?
It's actually every time you type :O
It's interpreting : O as an emoticon and converting it to an Emoji.

This is what the [ code ] tag is for. It will prevent such interpretations.
 
  • Haha
Likes jedishrfu
jedishrfu said:
Static variables are defined for the class itself not for the instances created by the class. Where they come in handy is when you have some common variable for all instances like a global in non C++ C code.

I‘ve used it to keep a count of instances as they are created and destroyed. I’ve also used it for common constants across all instances of a class.

here’s some more info online

https://www.tutorialspoint.com/cplusplus/cpp_static_members.htm
That's exactly what the program in the book does, keeping track of how many instance of the Class there are as it puts the variable in the Constructor so every Instance will call the constructor and increment the count.

thanks
 
  • Like
Likes jedishrfu
  • #10
DaveC426913 said:
It's actually every time you type :O
It's interpreting : O as an emoticon and converting it to an Emoji.

This is what the [ code ] tag is for. It will prevent such interpretations.

oh no, no o!

I fixed @yungman posts with the emoticon by replacing it with an O again.
 
  • #11
jedishrfu said:
oh no, no o!

I fixed @yungman posts with the emoticon by replacing it with an O again.
The link you gave on the tutorial is MUCH better than the book. I am actually going to use it in my notes for demonstration.

Thanks
 
  • Like
Likes jedishrfu
  • #12
Jarvis323 said:
And the rule makes sense. Actually no member variables (except static const) can be assigned outside of the member functions. The constructor is for initialization. But the constructor is called for each object. So you would have the same variable being initialized multiple times, which doesn't make sense.

I'm trying to figure out the use case for a non-const static variable initialized in the header. As pointed out, one can use a non-const static to keep track of the number of instances of a class, but this won't work if you keep setting it to zero again every time an object is created.

I confess that I didn't know C++ forbade this. I had no cause to even try it. What would such a thing be good for?
 
  • #13
One could use a static counter and if it’s zero then initialize static stuff in your constructor before incrementing the static counter. This would insure that there's no resetting of the other static data.
 
  • Like
Likes Vanadium 50
  • #14
So, for example, if you wanted to store the time that the first object of a given class was created, that would be a way to do it (if the language allowed it).

I can sort of see that, but I would be strongly inclined to use a mutator instead. I don't like logic in constrctors if it can be avoided. If something goes wrong, the constructor can't tell you.
 
  • Like
Likes jedishrfu

Similar threads

  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 8 ·
Replies
8
Views
1K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 35 ·
2
Replies
35
Views
4K
  • · Replies 36 ·
2
Replies
36
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
3
Views
1K
  • · Replies 52 ·
2
Replies
52
Views
4K
  • · Replies 36 ·
2
Replies
36
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K