Question

EDIT: declaring them private was a typo, I fixed it:

Relating to another question, if I declared a static variable in a class, then derived a class from that, is there any way to declare the static variable as individual per each class. Ie:

class A:
{
public:
static int x;
};
class B:A
{
public:
const static int x;
};

does that define TWO DIFFERENT static variables x, one for A and one for B, or will I get an error for redefining x, and if I do get an error, how do a I create two seperate static variables?

Was it helpful?

Solution

When you're using static variables, it might be a good idea to refer to them explicitly:

public class B:A
{
  public const static int x;
  public int foo()
  {
    return B::x;
  }
}

That way, even if the class "above" yours in the hierarchy decides to create a similarly-named member, it won't break your code. Likewise, I usually try to us the this keyword when accessing normal member fields.

Updated to use C++ syntax.

OTHER TIPS

That creates two separate static variables.

Note that you have implicitly declared these private:

class A:
{
  private:
  static int x;
};
class B:A
{
  private:
  const static int x;
};

Which means the variables are not in competition with each other.

As already said, that creates two separate variables :

A::x;

// and 

B::x;

In fact if you try to use just 'x' in a method of B, only the closer scope definition will be used until you are more precise :

#include <iostream>

class A
{
protected:
static int x;

public:
    A() { x = 7; }
};

int A::x = 22;

class B:A
{
static const int x = 42;

public:

    int a_x() const { return A::x; }
    int b_x() const { return B::x; }
    int my_x() const { return x; } // here we get the more local variable, that is B::x.
};

int main()
{
    B b;

    std::cout << "A::x = " << b.a_x() << std::endl;
    std::cout << "B::x = " << b.b_x() << std::endl;
    std::cout << "b's x = " << b.my_x() << std::endl;

    std::cin.ignore();
    return 0;
}

Outputs:

A::x = 7
B::x = 42
b's x = 42

Someone mentioned that accessibility might limit accessibility : making the base variable private will not make it accessible to the child class. However, if the variable have to be protected or public, use an explicit access method or rely on the local scope rule I just demonstrated.

If you want a static variable that is individual to each class that uses A - you can use a template class.
For e.g.

template<class T> struct A
{
   A() { ++s_var; }
   static int s_var;
};

template<class T> int A<T>::s_var;

stuct B :A<B> {
  B() { ++s_var; }  // this is a different s_var than the one used by 'C' below
};

struct C : A<C> {
  C() { ++s_var; } // this is a different s_var than the one used by 'B'
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top