Walt Walt - 1 month ago 15
C++ Question

passed this ptr turns to NULL in called function

I think there may be an issue with the way my constructors are working. Here is the problem:

--- in class_A.h file
#include "Class_B.h"

class_A
{
public:
Class_A();
~Class_A();
Class_B * m_pClass_B;
}

--- in class_B.h file
#include "Class_A.h"
class Class_A; //forward declaration

class Class_B
{
public:
Class_B();
~Class_B();
Class_A * m_pClass_A;
}

-- in the Class_A.cpp
#include "Class_A.h"
Class_A::Class_A() {}
Class_A::~Class_A() {}

Class_A::Run()
{
m_pClassB->Set_pClass_A(this); // <----- ? Problem here?
}

--- in class_B.cpp file
#include "Class_A.h"
Class_B::Class_B() {}
Class_B::~Class_B() {}
void Class_B::Set_pClass_A(Class_A * ptr) //<-- when here ptr is valid
{
m_pClass_A = ptr; // <--- once here, the ptr is NULL!!
}


I made a sample project of this issue in visual studio so I have a clear view during debugging. The 'this' ptr value is valid during the function call, but goes to NULL once we step into the function. It looks to me like there is some copy function that isn't occurring in the constructor, and that I should be explicitly doing something there, but not sure what.

Any feedback on what is wrong will be appreciated.

Also, after googling about, I see there may also be some compiler specific handling, but the issue occurs in both Windows 10 using MSVS 15 on a Win32 console app, and also in gcc compiling with -std=c++0x.

Thanks in advance!

Answer

In function void Class_B::Set_pClass_A(Class_A * ptr) pointer this points to object of class Class_B . But your m_pClass_B points to NULL (if you are lucky, because it's not initialised), so if you call Set_pClass_A, then you have your problem: this is NULL. There is everything ok with ptr.