Interview Question


Country: United States




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

That's how dynamic_cast works in conversions from base to derived only if base is polymorphic, or else a compile time error occurs. So, to make base polymorphic, just define it like this:

class base{
virtual void dummy();
};

Also, the whole example has numerous syntax errors. The correct example should look like this:

class base{
virtual void dummy();
};
class derived {};
int main()
{
base* b;
derived* d=dynamic_cast<base*>(b);
}

- Anonymous September 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

with out polymorphic,vtable,vptr

how can the runtime environment find whether they are related...

thats the reason dynamic_cast needs polymorphic code.

- gs September 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

dynamic_cast needs RTTI and RTTI is available only with polymorphic classes .

- kraj October 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

dynamic_cast has been designed only for inheritance hierarchy downcasting. Use static_cast or reinterpret_cast. However, reinterpret_cast is not portable across platforms.

- crystal.rishi2 October 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class base{ };
class derived : public base { };

int main()
{
    base* b;
    derived d;
    
    b = dynamic_cast<base*>(&d);
    
    return 0;
}

- BT August 02, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

class base{ virtual void dummy() {} };
class derived : public base { };

int main()
{
    base* pb ;
    derived* pd; derived d;
    
    pb = dynamic_cast<base*>(&d);
    
    pd = dynamic_cast<derived*>(pb);
    
    return 0;
}

base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.

- BT August 02, 2013 | Flag


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