i know you cannot understand anything from the title and i am sorry but i don't know how to say it because it's a little complicated, so i won't give details of my problem, i hope you can understand from the code
classB.h:
#ifndef CLASSB_H
#define CLASSB_H
class MainClass; // so we can declare a pointer of class B
class SecClass
{
public:
MainClass *m_MainClass;
SecClass( );
~SecClass( );
};
classB.cpp
#include "classB.h"
#include "classA.h"
//
// A
//
SecClass :: SecClass( MainClass nMainClass )
{
m_MainClass = nMainClass;
}
SecClass :: ~SecClass( )
{
m_MainClass->someFunct( );
}
classA.h:
#ifndef CLASSA_H
#define CLASSA_H
class SecClass; // so we can declare a pointer of class B
class MainClass
{
public:
SecClass *m_SecClass;
int m_ID;
MainClass( );
~MainClass( );
bool Update( );
void someFunct( ) { }
};
#endif
classA.cpp
#include <iostream>
#include "classA.h"
#include "classB.h"
//
// A
//
MainClass :: MainClass( )
{
m_SecClass = new SecClass( this );
}
MainClass :: ~MainClass( )
{
delete m_SecClass;
}
bool MainClass :: Update( )
{
// do stuff...
if( ... )
return true;
return false;
}
void main( )
{
MainClass *gMainClass = new MainClass( );
while( gMainClass->Update( ) )
{
// main program loop
}
delete gMainClass; // this will crash
}
so, i'll explain
MainClass creates a new instance of a SecClass
The SecClass creates a pointer to the main class( to access some funct/values )
when the main class destructor is called, the program deletes the SecClass too, but when the destructor of SecClass is called it occures a crash because it tryes to call a fuction of the main class whitch has been destroyed...
how can i avoid this unhappy case?
gMainClass = NULL; and checking for null class pointer in the SecClass destructor si not an option since we'd cause a memory leak