Please have a look at the following code.
GameComponent.h
#pragma once
#include<time.h>
#include "Position.h"
class GameComponent
{
public:
GameComponent(int);
GameComponent();
~GameComponent(void);
virtual void update(const tm*);
void addPosition(Position *p);
friend class Position;
private:
int id;
Position *position;
};
GameComponent.cpp
#include "GameComponent.h"
#include <iostream>
#include <time.h>
#include "DrawableGameComponent.h"
#include "Position.h"
using namespace std;
GameComponent::GameComponent(int v):id(v)
{
}
GameComponent::GameComponent(){}
GameComponent::~GameComponent(void)
{
}
void GameComponent::update(const tm* time)
{
cout << "ID : " << id << endl;
cout << "Update: " << time->tm_hour << ":" << time->tm_min << ":" << time->tm_sec << endl;
position->display();
//Position::displayPositions();
}
void GameComponent::addPosition(Position *p)
{
position = p;
p->display();
cout << "position working" << endl;
}
Position.h
#pragma once
class Position
{
friend class GameComponent;
public:
Position(int x, int y, int z);
Position();
~Position();
void display();
private:
int x;
int y;
int z;
};
Position.cpp
#include "Position.h"
#include <iostream>
using namespace std;
Position::Position(int x, int y, int z)
{
this->x = x;
this->y = y;
this->z = z;
}
Position::Position(){}
Position::~Position(void)
{
}
void Position::display()
{
//cout << "Display Working" << endl;
cout <<"Position " << " X: " << x << " Y: " << y << " Z: " << z << endl;
}
First, this is not the complete code, this is a part of the code where error occurred. When I run my code I get the error
Unhandled exception at 0x00302d90 in GameEngine.exe: 0xC0000005: Access violation reading location 0xcdcdcdd5.
It is pointing to the output area (cout << "X" << ........) of the display()
method of position
(Visual Studio shows a yellow array pointing to that place).
I googled this issue, and found this happens because of null pointers, where it points to no where. There is a pointer assigning (assigning pointer parameter to another pointer) inside GameComponent
's addPosition()
method.
I believe the error comes from there. Please help me to get rid of this error
Update
Following is the location where I cann addPosition()
Test.cpp
GameComponent **component;
void Test::add(GameComponent *gameComponent, Position *p)
{
component[componentCount] = gameComponent;
component[componentCount]->addPosition(p);
componentCount++;
}