How does the Virtual Differs in C++ and c#? basically i wanted to know is there any difference in the way Vtable is represented in C# and c++? Also is there any difference in the way the compiler creates the V Table in C# and c++?
Basically the interviewer wanted to know how does the compiler behaviour differrs for virtual functions in case of C# and c++.
I have answered the question mentioning there might be no difference in VTABLE expect that there is no Virtual Destructor in c#.
(1) In C# one can choose to
overrideavirtualfunction from base class. Both base and derived methods can have same syntax, but derived method can participate in polymorphism only if it uses the keywordoverridebefore it. See this answer for more details.In C++, if provided the same syntax method in derived class as base class
virtualmethod; then it will be automatically be overridden. No choice.(2) To be short, in C# we have
abstractmethods and in C++ purevirtualmethods. Both may not be exactly same, but are equivalent (as purevirtualcan have function body).(3) In C++ we have choice to call
virtualmethod without letting it participating in polymorphism. e.g. calling with an object, calling inside constructor.(4) In C++, if the base virtual method is
publicand derived method isprivatethan there is no difference forvirtualmechanism, when the method is called with base handle (pointer or reference). Which means that their access specifier can be different.Now coming to your 2nd question of how
vtables are implemented. This is not really an objective question. Because in C++ itself different vendors implement thevtablein different ways (it’s not in standard as pointed by @littleadve). So for interview sake you can answer that,vtables are platform dependent.