Goldman Sachs Interview Question
Software Engineer / Developerson memset to Foo object f it's vptr also be set to NULL.which is stored in the object's starting address.
I tried a little different version of the above code. And it ran smoothly, giving 10 and 0 as output.
class Foo
{
int a;
public :
Foo(){
a=10;
}
virtual int Fun1() { return a;};
};
class X
{
Foo f;
public:
X()
{
memset(&f,0x0,sizeof(f));
}
int Fun1() { return f.Fun1();};
};
int main()
{
Foo ob;
cout<<"\n"<<ob.Fun1();
X x;
cout<<"\n"<<x.Fun1()<<"\n";
return 0;
}
I think I preserved the logic of code given. Please correct me if I am wrong. I still don't understand what(if any) is the problem with that code.
@ anurag - Agree with you but does it cause any harm? I don't think so.
@JohnyCigar - yep, code works w/o any problem. even I am still thinking what problem this snippet has. I don't see any issue in executing the program.
This Qn costed my exit in second round.Interviewer grilled me a lot around this qn.He seemed to be fascinated by this Qn :-(
try calling the virtual function after u declare obj X. the function pointer in vtable will be set to 0 and will reference a null, not the fun1 function
Right, the problem with this code is that we're memsetting an object which has a virtual function.
@Vinnet
Thanks, you are right code crashes when f try to access Fun1() since Fun1() is virtual and memset has already reset the vptr of f to Null however if we remove virtual keyword from Fun1() then code works fine.
@RS & Vineet : When I compiled this code on VS it didn't crash. Virtual ptr concept will come if we are calling Fun1 with Fun object pointer. I modified code and changed Fun f to Fun *f.
If we try calling Fun1 now using ptr f, program will crash, since virtual pointer is set to null.
vptr gets created in both kind of objects (statically created or dynamically created)
class base{
int i;
virtual void show() {..}
};
1. Statically created:
base b;
2. Dynamically created:
base *b = new base();
Point is when you access any virtual function through these objects then vptr is used or not.
For case 1st - Vptr is not used. So even if vptr is NULL, still virtual function can be called, because there is no polymorphism.
For case 2nd Vptr is used. If Vptr is NULL , then calling to virtual function will give null pointer exception.
when the object of X class is getting initialized, the member of that class are initialized too, at that time default constructor of that f class is getting called, and after that with the memset statement we are going to access the private member, that's why it is not possible.
just think about only one error tat is main does not return anything ........and object is not allocated......
The major problem is the abuse of memset here. It erased the whole Foo object and it destroyed VPTR in Foo. So when you call virtual function, it will crash.
- xiaofeng.ustc January 28, 2013