I don’t want to use pointers when I don’t have to, but here’s the problem: in the code below if I remove the asterisk and make level simply an object, and of course remove the line level = new Level; I get a runtime error, the reason being that level is then initialized on the first line, BEFORE initD3D and init_pipeline – the methods that set up the projection and view for use. You see the problem is that level uses these two things but when done first I get a null pointer exception.
Is this simply a circumstance where the answer is to use a pointer? I’ve had this problem before, basically it seems extremely vexing that when a class type accepts no arguments, you are essentially initializing it where you declare it…. or am I wrong about this last part?
Level* level;
D3DMATRIX* matProjection,* matView;
//called once
void Initialise(HWND hWnd)
{
initD3D(hWnd);
init_pipeline();
level = new Level;
}
I’m coming from c# and in c#, you are simply declaring a name with the line Level level; arguments or not, you still have to initialize it at some point.
You are correct that if you do:
then
levelwill be instantiated at that point. That is because the above expression, which appears to be a global, isn’t just a declaration, but also a definition.If this is causing you problems because
Levelis being instantiated before something else is being instantiated, then you have encountered a classic reason why globals suck.You have attempted to resolve this by making
levela pointer and then “initializing” it later. Wjhat might suprise you is thatlevelis still being instantiated at the same point. The difference now is the type oflevel. It’s not aLevelanymore; now its a pointer-to-level. If you examine the value oflevelwhen your code entersInitializeyou’ll see that it has a value of NULL.It has a value of NULL instead of a garbage value because globals are static initialized, which in the case here, means zero-initialized.
But this is all somewhat tangential to the real problem, which is that you are using globals in the first place. If you need to instantiate objects in a specific order, then instantiate them in that order. Don’t use globals, and you may find that by doing that, you don’t need to use pointers, either.