Maybe you will be able to clear something for me, because I don’t know exactly where my thinking is flawed. First some code:
Talker.h:
class talker
{
public:
talker();
void sayHello() {cout << "Hello";} ;
};
anotherClass.h:
class anotherClass
{
public:
anotherClass();
void doSomethingYourself() { cout << "will do"; };
void askHimToSayHello() { pointerToTalker->sayHello; };
//Access violation, bad pointer(?)
};
common.h:
static talker *pointerToTalker;
// if I add here "= new talker", code works fine
main.cpp:
#include "common.h"
int main()
{
pointerToTalker = new talker; // Here is the bug, but why?
pointerToTalker -> sayHello; // says Hello alright
anotherClass *pointerToAnotherClass = new anotherClass;
pointerToAnotherClass -> doSomething (); //Does something OK
pointerToAnotherClass -> askHimToSayHello(); // Causes access violation
}
Of course functions are a bit more complex, and each is implemeted in coresponding .cpp including “common.h”. My question is – why pointerToTalker, if initialized inside main() does not work inside anotherClass::AskHimToSayHello()? It should pointing to valid memory by the time it is used there.
It is my “Hello world, OOP!” btw, so please be gentle if there is no hope for me 🙂
Sorry for the childish style btw. It helps me cut down the code I have to something more compact without me loosing the big picture :).
Because
is not a global. In this context,
staticgives the variable internal linkage for each translation unit (cpp file + included files) in whichcommon.his included.You need to declare it as
extern:and initialize it in a single implementation file.
Declaring it
staticwill create a copy ofpointerToTalkerfor each translation unit. So you’re initializing the one frommain.cpp. Others are left uninitialized, and thus you run into undefined behavior. The proper way is: