I have this error:
Exception thrown at 0x0108C6E9 in myprojectname.exe: 0xC0000005: Access violation reading location 0x00000028.
However, this only happens when I call a function from the base class via the derived class.
I need a pointer to the space object because my base class also needs that. I am not sure if this is needed.
This is how I call the functions of the base(Player) class:
space->getEnemy().drawPlayer(); //FIRST I GET THE OBJECT OF THE DERIVED(ENEMY CLASS) AND THAN I CALL A FUNCTION FROM THE BASE CLASS(PLAYER CLASSS)
The error message "Unable to read memory" happens in getter functions in a class that the base class needs(for example a pointer to the window).
Does anyone know what I am doing wrong?
I initialize that space pointer to my import class named Space, in every class of my project. The program works fine with those space pointers if I don't call the inherited stuff of Enemy class.
EDIT:
I found out that the object to the (very important) Space class, is NULL in the base class. The enemy class space object is not NULL, but the space object of the class it inherits from, is NULL. Does anyone know how an inherited pointer object can be NULL?
A picture to make it clearer:
EDIT 2 MY CURRENT CODE:
Enemy.h (THE DERIVED CLASS)
#pragma once
class Space;
class Enemy : public Player{
public:
void updateEnemy();
private:
};
Enemy.cpp
#include "Space.h"
#include "Enemy.h"
#include "Player.h"
#include <iostream>
void Enemy::updateEnemy(){
if (space == nullptr) {
std::cout << "null"; //IT PRINTS NULL
}
}
A part of player.h (THE BASE CLASS)
class Space; //forward declaration
public:
void init(Space * s);
protected:
Space * space;
A part of player.cpp
void Player::init(Space * s){ //INITIALIZING SPACE CLASS OBJECT
space = s;
}
Both your Player object and your Enemy object declare a
Space * space;
So Enemy::space
hides Player::space
so when you init Enemy::space
, Player::space
remains zero.
It is almost certainly a mistake to declare another Space * space
in the Enemy
class. You should be using the one in the Player
class. I expect the one in the Player
class was private
so you can't use it. But having another one doesn't fix that. Either change it from private
to protected
or make all accesses through an accessor function.
Edit: Wild guess, you want one Space * space
shared by all instances of the Player
class. To do that: Inside the definition of Player
you have:
static Space * space;
and elsewhere outside the definition of Player
(in some cpp file) you need:
Space* Player::space;
User contributions licensed under CC BY-SA 3.0