Question on static int variable

In summary: Tree{private: static int objectCount;}...you try to initialize it from within the class, you'll get an error. You need to initialize it in the cpp file, like this:int Tree::objectCount = 0;This way, the compiler will know that you're referring to the static variable.
  • #1
yungman
5,755
293
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
 
Technology news on Phys.org
  • #2
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
  • #3
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:
  • #4
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
  • #5
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.
 
  • #6
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
  • #7
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
  • #8
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
  • #9
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

FAQ: Question on static int variable

What is a static int variable?

A static int variable is a variable that holds an integer value and is declared using the keyword "static". It is a type of variable that is shared by all instances of a class and can be accessed without creating an object of that class.

Why would you use a static int variable?

A static int variable is useful when you want to store a value that is common to all instances of a class. It can also be used to keep track of a count or to store a constant value that is used throughout the program.

How do you declare a static int variable?

To declare a static int variable, you would use the following syntax: static int variableName; This should be done within a class, but outside of any method or constructor.

Can a static int variable be changed?

Yes, a static int variable can be changed. However, the value will be changed for all instances of the class, not just the specific instance that made the change. It is important to keep this in mind when using static variables.

What is the difference between a static int variable and a non-static int variable?

The main difference is that a static int variable is shared by all instances of a class, while a non-static int variable is unique to each instance of the class. Additionally, a static int variable can be accessed without creating an object of the class, whereas a non-static variable can only be accessed through an object.

Similar threads

Back
Top