27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

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

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

pg 76<br />

SOLUTION<br />

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

»»<br />

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

»»<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!