If I have a static variable in a class e.g. a pointer to another class like this: (B is another class)
1 2 3 4 5
class A
{
public:
static B* cB;
};
Then I set that variable and create multiple instances of class A like this:
1 2
A::cB = new B;
As = new A[Number];
Then will the value of cB be the same across all instances?
I cannot pass the class pointer in the constructor as I need to create an array of instances. I tried this method but I get linker error.... unresolved external.
Static data members are not associated with any specific instance.
You don't need a static variable like this. For one, you can call a different constructor than the default constructor when you make an array, and for two, you should be using std::vector.
Yeah but in the default constructor it needs the pointer to another class... so I have to somehow set that static variable before I create the instances.
But can I do it with a static variable? Because I could be creating a large number of instances, and having a static variable could save a bit of memory. And IMO it would be easier.
Your question is not "How can I set a static variable in a class during runtime", it is "Why do I get an unresolved external symbol error when I try to link my program?"
You need to provide a definition for the static variable in one and only one cpp file (because static variables are basically globals in a class scope)