inheritance and destructors

Hey all,

I’m having trouble calling child class destructors and was hoping someone could give me some insight.

I have a base class called Caller and two Caller sub-classes, SoftCaller and SquareCaller. In my main class I have a map of Callers called callers, and it holds SoftCallers and SquareCallers.

  
  
if (ofRandomf() < .5f) {  
    callers[_id] = new SquareCaller(_x, _y);  
} else {  
    callers[_id] = new SoftCaller(_x, _y);  
}  
  

Later in the program, I sometimes need to delete these.

  
  
map<string, Caller*>::iterator it = callers.find(_id);  
Caller* s = it->second;  
delete s;  
callers.erase(_id);  
s = NULL;  
  

Now this only calls ~Caller() and not ~ SoftCaller() or ~SquareCaller(). I thought maybe making ~Caller() virtual would work but that just makes the app crash whenever I construct a SoftCaller or SquareCaller.

I found a workaround, which is to make a virtual destroy() method and have that call the destructor, but I was hoping there is a more elegant solution.

  
  
//--------------------------------------------------------------  
void SoftCaller::destroy() {  
    delete this;  
}  
  

Thanks!

[quote author=“prisonerjohn”]Hey all,

I have a base class called Caller and two Caller sub-classes, SoftCaller and SquareCaller. In my main class I have a map of Callers called callers, and it holds SoftCallers and SquareCallers.
[/quote]

Declare the base class’ destructor virtual ala

  
  
  
class Caller {  
public:  
...  
virtual ~Caller();  
};  
  

cheers,
Stephan

Hey Stephan,

As I said, for some reason when I do this it crashes my app whenever I construct a SoftCaller or SquareCaller.

I’m pretty sure this is unrelated to the rest of my code as it works fine if I just take out the “virtual” keyword.

Thanks!

HI,

[quote author=“prisonerjohn”]Hey Stephan,

As I said, for some reason when I do this it crashes my app whenever I construct a SoftCaller or SquareCaller.

I’m pretty sure this is unrelated to the rest of my code as it works fine if I just take out the “virtual” keyword.

Thanks![/quote]

There must be something wrong with your code, because virtual destructors are so fundamental in c++, they just work. can you provide a stack-trace of the crash when you are using virtual destructors?

If you are on mac os x, try running with libmallocdebug, to catch any wrong memory allocations.

cheers,
Stephan

It’s funny I was just wondering why there is so few virtual destructor in common OF source code, just a little reminder about this point:

http://en.wikipedia.org/wiki/Virtual-fu-…-estructors

Under Windows I’ve got a lot of crashes linked to vftable which is linked, if I remenber rigth, to this problem of non virtual destructors in base classes