Role of compiler for Virtual functions in C++

124 views Asked by At

Recently I attended an interview. The interviewer asked me to explain virtual function mechanism in C++. I explained using VPTR and VTABLE. I explained in detail how VPTR and VTABLE are used to achieve run time polymorphism.

While I was explaining how the compiler introduces hidden code to fetch VPTR from the class, get function address from VTABLE and call is resolved. But he was not satisfied with the answer. He asked me detail of hidden code? What exactly does a compiler do? If a compiler is doing everything for you then what is the use of developer?

I searched for details of the role of a compiler for virtual functions. Regarding the hidden code. But still not clear about the question.

Please, any help or pointers?

1

There are 1 answers

0
dlask On

If a compiler is doing everything for you then what is the use of developer?

Developers are there to specify their intentions and compilers are there to transform the intentions to executables. As time passes, computers get faster and compilers smarter so there is no need to express developer's intentions in assembly code but in Erlang, F#, Prolog, whatever.

In other words, it's interesting to know details of the code produced by C++ compilers, but it is not the core of C++ development.

Finally, to answer the quoted question:

Compilers are not doing everything yet. Unfortunately.