Class problem (again)

Started by
4 comments, last by Attala101 18 years, 1 month ago
Hi I have made av simple class calles "nationclass". In the header file I define it like this:

#ifndef NATIONCLASS_H
#define NATIONCLASS_H

class nationclass
{
public:

	nationclass();
	~nationclass();
	
	void init( );

	int ICBMbigCount, ICBMmediumCount, ICBMsmallCount;

private:

};


#endif

My .cpp file looks like this:

#include "nationclass.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

nationclass::nationclass( )
{
	ICBMsmallCount = 0;
	ICBMmediumCount = 0;
	ICBMbigCount = 0;

}

nationclass::~nationclass()
{
   
}

void nationclass::init ( )
{


	int i;
	for (i=0; i < 3; i++)
	{
	int r;
	r = (rand() % 3) + 1;
	switch (r)
	{
	case 1:
		{
		ICBMsmallCount++;
		break;
		}
	case 2:
		{
		ICBMmediumCount++;
		break;
		}
	case 3:
		{
		ICBMbigCount++;
		break;
		}
	}
	}
}

It all compiles fine but when I try to call the memberfunction init() it says that the public ints ICBMbigCount, ICBMmediumCount and ICBMsmallCount cannot be evaluated. (Access violation reading location 0x00000000). Can anybody see what I'm doing wrong?
Advertisement
Sounds like a null pointer error. What does the calling code look like.

Also:
Quote:#include <time.h>
#include <stdio.h>
#include <stdlib.h>

#include <ctime>
#include <cstdio>
#include <cstdlib>

Or even just

#include <cstdlib>

since rand is the only standard function you use. This is C++, not C.

Σnigma
I guess you are calling the init something like this:

nationclass_pointer->init();

If thats the case, make sure the nationclass_pointer is valid (not pointing at address NULL)
Well In my game.h file I do this:

class nationclass;
extern nationclass * USA;

In my game.cpp file:

nationclass * USA;

And in a function calles game_init() I go:

USA->init();
USA is a pointer, but it doesn't actually point to anything. You need to allocate an object of type nationclass and point USA at it somewhere:

USA = new nationclass();

and don't forget to delete it later!

Σnigma
Aha, silly me :) Forgot to do that.

Thanks guys!

This topic is closed to new replies.

Advertisement