25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 13 | C++<br />

13 7 Why does a destructor in base class need to be declared virtual?<br />

SOLUTION<br />

Calling a method with an object pointer always invokes:<br />

» <strong>the</strong> most derived class function, if a method is virtual<br />

2 2 1<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Knowledge Based<br />

pg 76<br />

» <strong>the</strong> function implementation corresponding to <strong>the</strong> object pointer type (used to call <strong>the</strong><br />

method), if a method is non-virtual<br />

A virtual destructor works in <strong>the</strong> same way A destructor gets called when an object goes out<br />

of scope or when we call delete on an object pointer<br />

When any derived class object goes out of scope, <strong>the</strong> destructor of that derived class gets<br />

called first It <strong>the</strong>n calls its parent class destructor so memory allocated to <strong>the</strong> object is properly<br />

released<br />

But, if we call delete on a base pointer which points to a derived class object, <strong>the</strong> base class<br />

destructor gets called first (for non-virtual function) For example:<br />

1 class Base {<br />

2 public:<br />

3 Base() { cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!