The problem below is not very common, so I can’t find anything online that could be of help:
I have class parent, which must have the default constructor and destructor, I am not supposed to define anything about these two members.
I need to take control of ptr destruction, it must be destructed only if it is not referenced, which is controlled by counter in someclass.
class parent {
public:
someclass * ptr;
}
class child: public parent {
~child() { //<-- this line
cout<<"in ~child!"<<endl;
if(this->ptr == NULL) cout<<"ptr is NULL"<<endl;
this->ptr->delete_reference(); //<-- here ptr = NULL
}
someclass* get_ptr() {
return this->ptr;
}
}
class someclass {
void delete_reference() {
counter--;
if(counter == 0) delete this;
}
The problem is that in this line parent’s default destructor is called and does ptr = NULL, as a result, ptr is not properly destructed.
Is there a way to skip the call of ~parent with these restrictions?
I also tried to remove inheritance, and have an instance of parent in child, but the same thing happens, parent’s destructor is called again.
Furthermore, I need ptr in parent because there are more child classes and they need to share this information.
Thank you!
EDIT:
OK as I understood, I got something wrong here… the problem is how ptr gets NULL.
As long as I confused the order of destructor calls, then the problem is not in this line.
void function() {
child ch1;
for(int i = 0; i<1; i++) {
cout<<iterating<<endl;
do_some_work(ch1);
}
if(ch1->get_ptr() != NULL) cout<<"ptr is OK"<<endl;
return;
//Here is the destructor ~child called (?)
}
int main() {
function();
}
The above calling is the way I use child. Inside do_some_work there is actually a lot of work that is difficult to describe here.
The point is that after do_some_work finishes, ptr is OK. Then I suppose destructors are called and ptr seems to be NULL.
So, the above will print:
iterating
ptr is OK
in child
ptr is NULL
Segmentation fault
Is there any explanation after this edit?
Thank you all very much!
No.
And No.
First, the parent’s destructor (default or otherwise) is called after the child’s, not before.
Second, the the parent’s default destructor probably doesn’t set
ptrtoNULL. It probably doesn’t touchptrat all. (I say “probably”, because there is no way of knowing. Referencingptrat all after the parent destructor returns is undefined behavior.)I suggest that you have come to an incorrect conclusion. Please post a short complete program that demonstrates your problem and we can help you arrive at the correct conclusion.