Reputation: 299
Heres my problem, if I pass a variable from class A to class B via function, then in class B pass that variable to other functions for testing then it works fine. But if I pass the variable from A to B then try assigning it to a variable in class B, it gives the error for no reason
//Globals.h
enum TypeofObject { CIRCLE, SQUARE, RECTANGLE, DIAMOND };
//Object.h
#include "Globals.h"
class Object
{
void Update();
private:
TypeofObject currentObject;
CollisionDetection * gameCollision;
};
//Object.cpp
void Object::Update()
{
//Do stuff here
gameCollision -> testCollision(currentObject);
}
//CollisionDetection.h
#include "Globals.h"
class CollisionDetection
{
public:
void testCollision(TypeofObject currentObject);
private:
void checkObjects(TypeofObject currentObject);
TypeofObject currentObject;
}
//CollisionDetection.cpp
void CollisionDetection::testCollision(TypeofObject curObject)
{
currentObject = curObject; //<- If I have this then it gives access violation error
checkObjects(curObject); //<- Passing it from one function to the next works
//fine but I want to assign it to currentObject so
//it doesnt need to be passed
}
Upvotes: 1
Views: 1333
Reputation: 3560
I assume the issue here is that Object::gameCollision
has not been initialised. The CollisionDetection::testCollision
function is called correctly because you can imagine member functions as regular function taking an extra hidden parameter:
void CollisionDetection_testCollision(CollisionDetection *this,
TypeOfObject curObject);
Given your definition, the function will run correctly up until the point where this
is accessed:
currentObject = curObject; // this->currentObject = curObject
The line above is trying to set some memory at an offset from the this
object. If this
is not correctly initialised, the function will fail with an access violation.
I presume that checkObjects(curObject)
does not fail because you are not accessing any of the data members of CollisionDetection
in that function.
Upvotes: 2