Destructors with inherited classes -- "Destructors 101"?
-
Suppose I have a parent class CParent. Suppose I have two other classes, CChildA and CChildB, which both inherit from CParent. Suppose I need to load two instances in memory, but other application conditions affect whether I'm working with CChildA or CChildB. This is obviously do-able with polymorphism like this: CParent *pChildX = 0, *pChildY = 0; At some point later I can make the appropriate assignments according to my application conditions: pChildX = new CChildA(); pChildY = new CChildB(); My question is, what happens when run this code: delete pChildX; delete pChildY; Is the child object fully deleted? I think it would, but it I'm confusing myself by thinking somehow only the CParent component of the data would be deleted, and that there would be a memory leak since the "delete" was not called on explicit CChildA or CChildB variables. Please someone tell me I'm overthinking this.
-
Suppose I have a parent class CParent. Suppose I have two other classes, CChildA and CChildB, which both inherit from CParent. Suppose I need to load two instances in memory, but other application conditions affect whether I'm working with CChildA or CChildB. This is obviously do-able with polymorphism like this: CParent *pChildX = 0, *pChildY = 0; At some point later I can make the appropriate assignments according to my application conditions: pChildX = new CChildA(); pChildY = new CChildB(); My question is, what happens when run this code: delete pChildX; delete pChildY; Is the child object fully deleted? I think it would, but it I'm confusing myself by thinking somehow only the CParent component of the data would be deleted, and that there would be a memory leak since the "delete" was not called on explicit CChildA or CChildB variables. Please someone tell me I'm overthinking this.
Never mind. I just answered my own question. The answer is my application has memory leaks coming out of my ears. I just found an article that explains you need the keyword "virtual" in your destructor declaration. I haven't been doing that. Shame, shame, shame! In case anyone else finds it useful, here's the link to the article.