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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

13.3 How do virtual functions work in C++?<br />

pg 76<br />

SOLUTION<br />

A virtual function depends on a “vtable” or “Virtual Table”. If any function of a class is declared<br />

as virtual, a v-table is constructed which stores addresses of <strong>the</strong> virtual functions of this class.<br />

The compiler also adds a hidden vptr variable in all such classes which points to <strong>the</strong> vtable of<br />

that class. If a virtual function is not overridden in <strong>the</strong> derived class, <strong>the</strong> vtable of <strong>the</strong> derived<br />

class stores <strong>the</strong> address of <strong>the</strong> function in his parent class. The v-table is used to resolve <strong>the</strong><br />

address of <strong>the</strong> function, for whenever <strong>the</strong> virtual function is called. Dynamic binding in C++<br />

is <strong>the</strong>refore performed through <strong>the</strong> vtable mechanism.<br />

Thus, when we assign <strong>the</strong> derived class object to <strong>the</strong> base class pointer, <strong>the</strong> vptr points to <strong>the</strong><br />

vtable of <strong>the</strong> derived class. This assignment ensures that <strong>the</strong> most derived virtual function<br />

gets called.<br />

1 class Shape {<br />

2 public:<br />

3 int edge_length;<br />

4 virtual int circumference () {<br />

5 cout circumference(); // prints “Circumference of Triangle Class”<br />

21 }<br />

In <strong>the</strong> above example, circumference is a virtual function in shape class, so it becomes virtual<br />

in each of <strong>the</strong> derived classes (triangle, rectangle). C++ non-virtual function calls are<br />

resolved at compile time with static binding, while virtual function calls are resolved at run<br />

time with dynamic binding.<br />

2 1 7<br />

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

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

Saved successfully!

Ooh no, something went wrong!