Question:
Say we have a class overridden in three steps, from class A to B to C. If I do like this:
B* b = new C; delete b;
Will this free the memory allocated by "new C"?
Answer:
make the base class destructors as virtual Source: CoolInterview.com
Answered by: sourish | Date: 8/20/2010
| Contact sourish
No, Because here "b" is the name of the object. We cant delete "b" for allocation of "c". Source: CoolInterview.com
Answered by: Md. Sajid khan | Date: 8/24/2010
| Contact Md. Sajid khan
Yes, and C class destructor will run too. This is polymorphism case where base ptr pointing to derived class obj. And if C class has a virtual destructor then B class destructor will too run (to do any user defined cleaning).
cheers, sm Source: CoolInterview.com
Answered by: sm | Date: 8/28/2010
| Contact sm
Some clarification about my last answer: again Yes, and C class destructor will also run if and only if base class B has a virtual destructor. This is polymorphism case where base ptr pointing to a derived class obj. PLEASE ignore the other comment "And if C class ..."
cheers, hm Source: CoolInterview.com
Answered by: sm | Date: 9/2/2010
| Contact sm
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|