Lets say there is a base class pointer which is pointing to a base class object:
baseclass *bptr;
bptr= new baseclass;
now if i do
bptr= new derived;
what is the problem here?
Lets say there is a base class pointer which is pointing to a base class object:
baseclass *bptr;
bptr= new baseclass;
now if i do
bptr= new derived;
what is the problem here?
The obvious answer is that you're leaking the original base class object.
You are reassigning the pointer without releasing the memory allocated for the previous object. This can result in memory leak, in case no body else has stored the value of bptr
before reassigning it.
In first line, you declared a pointer. In second line, you give it a reference in memory. in line 3, you give IT another reference in memory.
the first reference you gave to the pointer is leaked...you can never get it back.
Does baseclass
have a virtual destructor? If not, that could be bad too (in addition to obvious leak).
Other than the obvious memory leak it depends on the definition of baseclass
and derived
some of the problems could be:
derived
is not publicly derived from baseclass
(if so it's a horrible question to ask in an interview)baseclass
does not have a virtual destructor (in which case it's unsafe to delete bptr;
)Was he trying to get to the Circle Ellipse problem? If derived is a specialisation of baseclass some public methods on baseclass may no longer have a meaning e.g. if Circle is derived from Ellipse and Ellipse has a method called stretch() which stretches the ellipse in one axis, what do you do when the method is called on an instance of Circle?
The only problem occurs if the class destructor is not defined as virtual. In this scenario, it will cause memory leak
There is no syntax problem but you are loosing the address of the "baseclass" instance by assigning a new value to "bptr" variable. This results in a memory leak, as the address of the first instanciated class is lost.
If I were you I would turn back and ask your interviewer couple of questions:
And please, having virtual destructors etc come into place only if you have the class definitions. Perhaps the interviewer is secretly looking for clairvoyant types.
Arpan
what is the problem here?
If the answer of ("a memory leak") is not accepted, the problem is either the question or the interviewer ;)
I'd answer this interview question like so:
From the limited code snippet provided it's clear that a memory leak will ensue when we assign the pointer to an instance of this derived class, as we have no other pointers accessing the base object. However it's impossible to say anymore about the code snippet without seeing the definitions of both classes, and seeing the relationship between the two classes.