i have a variable that i prefer to declare in a cpp file instead of the header file. It should be accessible to objects of that class only. This variable should have a separate copy for every object of that class. Inheritance is not necessary.
Normally, I'd just declare it in the class definition.
A.h:
class A {
private:
int number;
}
But, can I do this instead?
B.h:
class B {
private:
// nothing
}
B.cpp:
static int number;
No, if you take the second approach, you're making it a static variable, which means you won't have a different copy for each object of that class (they'll all share that variable).
Either way, if it should only be accessed by that class, it should go in the class declaration, and should not be a global variable. By making it a static global variable, you're restricting access just to the scope of the file, not to the class. As good programming practice, try using as few global variables as possible.
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