I have a base class with a static pointer member. When I assign that static pointer member in a derived class, that static member appears NULL when referenced from the methods of the base class.
This is not the behavior I expect. Shouldn't the static pointer member still be assigned regardless of where it is accessed from? Am I wrong about the expected behavior?
The static member is a pointer to a base class. I realize that what I am trying to achieve is probably best accomplished by static polymorphism using templates ( Static polymorphism definition and implementation ) but I still do not understand why in this scenario the pointer member itself is NULL.
Edit: the behavior is NOT demonstrated in this SSCE. What bugs or common errors would cause the behavior I describe? My actual production scenario is significantly more complicated than this, but the structure is almost exactly the same. I am literally in the VS2010 debugger observing Base::staticMember == not null
, then call to Base::staticMethod()
, and inside Base::staticMethod()
, Base::staticMember
is null. I am baffled.
#include <iostream>
class Base {
public:
static Base *staticMember;
static void baseMethod();
};
Base *Base::staticMember = NULL;
class Derived : public Base {
public:
void derivedMethod();
};
void Base::baseMethod() {
// here staticMember == NULL, the unexpected behavior
if(staticMember == NULL) {
std::cout << "NULL";
} else {
std::cout << "NOT NULL";
}
};
void Derived::derivedMethod() {
staticMember = new Derived();
}
int main(int argc, void *argv[]) {
Derived *derived = new Derived();
derived->derivedMethod();
Base::baseMethod();
}