C++ Virtual Methods, Destructors, and Constructors Interview Question
November 13th, 2009
In a technical interview, you are likely to get questions which are meant to determine your knowledge of Object Oriented Programming. One common question is some variation on, “In C++, explain what virtual methods, virtual destructors, and virtual constructors are.” In general a good approach is to give a verbal, summary answer first, and then if the interviewer wants additional detail you can start showing some code. Virtual methods come into play when you 1.) have OOP inheritance, and 2.) have a subclass which has a method with the same name as a method in the base class, and 3.) you have a pointer which is declared as type pointer to the base class but is instantiated to point to an instance of the subclass. Without using the keyword virtual, a call to the subclass method will invoke the method with the same name in the base class, which is probably not the desired behavior. The solution is to declare the method in the base class as “virtual”. Virtual destructors come into play when 1.) you have OOP inheritance, and 2.) the base class uses dynamic memory allocation, and 3.) the subclass also uses dynamic memory allocation, and 4.) you have a pointer which is declared as type pointer to the base class but is instantiated to point to an instance of the subclass. Without using the keyword virtual, when you call “delete” on the pointer to the subclass object to invoke the destructor, the base class destructor would not be called, resulting in a memory leak. The solution is to declare the base class destructor as “virtual”. Finally, there is no such thing as a virtual constructor — trick question.
Entry Filed under: Interviewing
Trackback this post