Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static variables in a base class shared by all derived classes?

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?

like image 712
mpen Avatar asked Sep 07 '09 20:09

mpen


People also ask

Are static variables shared between classes?

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.

Are static variables shared by all objects of a class?

Class Variables and MethodsA static variable is shared by all instances of a class. Only one variable created for the class.

Are static variables shared?

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.

Do derived classes inherit static members?

static member functions act the same as non-static member functions: They inherit into the derived class.


1 Answers

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(); 
like image 190
Greg Hewgill Avatar answered Oct 09 '22 20:10

Greg Hewgill