If I have something like
class Base { static int staticVar; } class DerivedA : public Base {} class DerivedB : public Base {}
Will both DerivedA
and DerivedB
share the same staticVar
or will they each get their own?
If I wanted them to each have their own, what would you recommend I do?
A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created. Static variables occupies less space and memory allocation happens once.
Class Variables and MethodsA static variable is shared by all instances of a class. Only one variable created for the class.
Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.
static member functions act the same as non-static member functions: They inherit into the derived class.
They will each share the same instance of staticVar
.
In order for each derived class to get their own static variable, you'll need to declare another static variable with a different name.
You could then use a virtual pair of functions in your base class to get and set the value of the variable, and override that pair in each of your derived classes to get and set the "local" static variable for that class. Alternatively you could use a single function that returns a reference:
class Base { static int staticVarInst; public: virtual int &staticVar() { return staticVarInst; } } class Derived: public Base { static int derivedStaticVarInst; public: virtual int &staticVar() { return derivedStaticVarInst; } }
You would then use this as:
staticVar() = 5; cout << staticVar();
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