Bloomberg LP Interview Question
InternsCountry: United States
Interview Type: In-Person
bkumar.kcumca doing upvote of Rahul's post right now everywhere
good jobs to Rahul for self upvote
--- but NOT virtual constructors
it's not true. Borland Builder C++ has virtual constructor to support Delphi VCL library
V-table are built per class (not per object). That is not the correct reason for not having virtual constructor.
The reason is that compiler must know the object type at compile time (which is violated in case of virtual constructor). Hence there cannot be virtual constructors.
Consider this:
Base * a;
a = new Derived();
The v-table mechanism comes into picture after the base class pointer is set to the derived class object and calls something e.g a virtual function. However, for the base class pointer to be set to the derived class object, the object has to exist in the first place. Hence, making the constructor virtual would create a kind of deadlock. Anyway, there is no need for a virtual constructor.
/* using Microsoft Visual Studio 2010 */
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
//#define __NO_VIRTURAL_DESTRUCTOR
typedef unsigned int Positive;
class Base
{
public:
Base(){ cout<<"Constructing Base\n";}
#ifdef __NO_VIRTURAL_DESTRUCTOR
// this is a destructor:
~Base(){ cout<<"Base destructor called\n";}
#else
// this is a virtual destructor:
virtual ~Base(){ cout<<"Base virtual destructor called\n";}
#endif
};
class Derive: public Base
{
public:
Derive(){ cout<<"Constructing Derive\n";}
~Derive(){ cout<<"Destroying Derive\n";}
};
/*
* programmerinterview_dot_com/index.php/c-cplusplus/virtual-destructors/
* Well, what we can do is make the base class destructor virtual,
* and that will ensure that the destructor for any class that derives
* from Base (in our case, its the "Derive" class) will be called.
*/
void main()
{
Base *basePtr = new Derive();
delete basePtr;
cin.get();
}
/* results: using virtual destructor
* Constructing Base
* Constructing Derive
* Destructing Derive
* Base virtual destructor called
*
* results without using virtual destructor:
* Constructing Base
* Constructing Derive
* Base virtual destructor called
*/
In C++ you can have virtual destructors but NOT virtual constructors. This is because when an object has virtual functions it must have an associated v-table which keeps track of the addresses to the virtual functions for that class. That would mean that an object must be instantiated firstly before a v-table for that object could exist. Since constructors are intended to instantiate and create the object there can be no virtual constructor.
- Rahul September 27, 2013On the other hand a virtual destructor is allowed and should be used when ever there are virtual methods in the base class. The misuse of virtual destructors can lead to memory leaks and bad side effects