Interview Question for SDE-2s


Team: abc
Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
1
of 1 vote

This has to do with the type casting and the fact that your C::fun3 is virtual. Somehow B::fun1 is overriding the virtual C::fun3. If you cast your void* obj to the correct type, or remove the virtual keyword from C::fun3 you will get the expected output. Sorry I cannot provide a better explanation.

- Steve August 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

when you typecasted to void*, all info about D's layout got lost. So now when you are again type casting to C*, it just sets the pointer, but the vtable info is for D, compiler didn't do any adjustment because of the typecast, so when calling the method, it just calls whatever method it found in the offset location, which is undefined because a void* was not supposed to have any info

- abasu August 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

You have created D form both A and C, and their virtual tables are combined.
so virtual table for D looks like [fun1,fun2,fun3]

When compiler see d->fun3() it is compiled to "call 3rd function in virtual table"

But with that casting through void* you lost the type information.
at this point C* c = (C*)obj compiler doesn't know what obj is, it just assumes that first item is a pointer to virtual table and second one is z.
So c->fun3() is compiled to "call 1st function in virtual table"

First function in virtual table is fun1.

P.S. try to add variable "int w;" to class A then change c->z in "other" then check what d->w is :).

- Anonymous August 29, 2015 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More