The following code works (on ideone, Borland BCB 6 and gcc)
#include <stdio.h>
class Base {
private:
Base **BPtr;
public:
Base(void *Ptr) {
BPtr = (Base **)Ptr;
*BPtr = this;
}
virtual ~Base() {
if(BPtr) *BPtr = NULL;
printf("Base aufgelöst\n");
}
};
class Child : public Base {
public:
Child(void *Var) : Base(Var) {}
~Child() {
printf("Child aufgelöst\n");
}
};
int main() {
Child *Ptr = NULL;
new Child(&Ptr);
printf("Childptr: %p\n", Ptr);
delete Ptr;
printf("Childptr: %p\n", Ptr);
return 0;
}
The output of above program is:
Childptr: 0x9cc0008
Child aufgelöst
Base aufgelöst
Childptr: (nil)
which is exactly what I expected and want.
My question is simple: Is this actually safe or does it only seem to work? Because it does feel a little bit hacky to first implicitly cast a Pointer of type Child
to a void *
and then cast it to a Base **
or are there any obvious (or hidden) problems with this?
Thank you very much.
Edit: Since there seemed to a bit of a misunderstanding regarding my intention:
The sole purpose of this 'hack' is to NULL
the variable in question, once the object gets destroyed to protect myself against accidentally forgetting to NULL the variable manually and possibly accessing invalid memory later on.
The variable must and will not be used to access any other functionality of the classes.
However, what I also tried (and worked) before was the following:
void FreeFunc(void *Ptr) {
if(Ptr) {
Base **BPtr = (Base **)Ptr;
delete *Ptr; //Calls Destructors
*Ptr = NULL;
}
}
Which appears to be even worse from the replies I had been getting on here so far?