This was the question asked to me in one of the interviews.
If Vtable is created in compile time, and vptr
is assigned to object in runtime, then why compiler gives compile time error if we have virtual constructor in our class?
I explained whole mechanism. But he was more interested in 'Why compile time error not runtime error'
I told him the that the C++ guidelines are chalked such that so compiler sends error at compile time.
Can you please provide me the reason for the same
Why compile time error not run time error?
A runtime error occurs when an exception scenario occurs at runtime. While a compile time error occurs when the compiler detects that particular construct is not allowed by the C++ standard as valid C++ construct.
The C++ Standard does not allow constructor to be marked as virtual
. Hence the compiler detects it as violation of language grammer rules and flags an error.
As to answer why virtual constructor is not allowed in C++.
Bjarne answers the Q on his faq page as:
A virtual call is a mechanism to get work done given partial information. In particular, "virtual" allows us to call a function knowing only any interfaces and not the exact type of the object. To create an object you need complete information. In particular, you need to know the exact type of what you want to create. Consequently, a "call to a constructor" cannot be virtual.