C++ Static Variable Issues

Hi there! I’m currently having some issues when attempting to make a static variable. I have experience in Java and so my understanding of a static variable is something that affects every object of a class and is the same for each object. I am trying to do this for a boolean as shown in the code:

static bool color;

However I’m not entirely sure how to initialize the boolean. Whenever I try I just get a compiler error screaming at me for an unidentified variable. I would love if one of you guys could give me a hand in figuring this out.

Hey DinosaurDan,

Where are you attempting to declare your static boolean?

Also, what exactly are you trying to use the bool for?

I assume you are in a class.

initialise in cpp file by…

bool classname::color = true

I am using the bool as a way to switch between if statements within the “Puzzle” template. I am also trying to declare it here:

and am trying to initialize it here:

Hey DinosaurDan,

One thing you could try is to declare the variable inside of the function that you’re looking to use it in. When I did that it seemed to work fine for me.

What I did was create the variable at the top of the .cpp file and then I was able to use it throughout the functions that I wanted to use it in without any compiler errors.

Here’s some good reading regarding the static keyword also, if you’re interested: The Many Meanings of the C++ “Static” Keyword – Dave Smith's Blog

Have a great day