Question on static int variable

  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    Static Variable
Click For Summary

Discussion Overview

The discussion revolves around the use of static member variables in C++ classes, specifically focusing on their declaration, initialization, and the implications of their access modifiers. Participants explore the rules governing static variables, their scope, and the challenges faced when trying to initialize them within class definitions.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • Some participants express confusion about why initializing a static member variable directly in the class definition results in a compilation error.
  • Others explain that static member variables must be initialized outside the class definition in the implementation file to avoid multiple definitions.
  • A participant suggests that using static variables can lead to issues when multiple instances of a class are created, as they share the same static variable.
  • Some participants propose alternative designs, such as using a TreeNode class to manage instance-specific data instead of relying on static variables.
  • There is mention of the special case for static member variables, indicating that they are treated differently from instance variables, particularly regarding their initialization.
  • One participant notes that the rules around static variables can feel arbitrary and confusing, especially when considering access modifiers like private.
  • Another participant highlights the utility of static variables for maintaining a count of instances or for shared constants across instances.

Areas of Agreement / Disagreement

Participants generally agree on the technical rules surrounding static member variables but express differing opinions on their practical use and implications for class design. The discussion remains unresolved regarding the best practices for using static variables in class design.

Contextual Notes

Participants mention limitations in understanding the initialization process for static variables and the implications of access modifiers, indicating a need for clarity on these concepts. There is also a recognition of the complexity involved in managing static variables across multiple files.

Who May Find This Useful

Readers interested in C++ programming, particularly those learning about class design, static member variables, and object-oriented principles may find this discussion beneficial.

yungman
Messages
5,741
Reaction score
291
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   Reactions: 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   Reactions: 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   Reactions: 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   Reactions: 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   Reactions: 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   Reactions: 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   Reactions: 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   Reactions: 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   Reactions: jedishrfu

Similar threads

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