Interview Question: False Return

Sample Question #181 (programming – C++)

What’s wrong with the following C++ code? Here, Quant is a class already defined.

Quant & mycp(Quant & mm)
     Quant newmm;
     newmm = mm;
     return newmm;

How would you fix the problem?

This entry was posted in Sample Qs. Bookmark the permalink.

One Response to Interview Question: False Return

  1. Brett says:

    Variable newmm only exists in the function, so the return statement returns a reference to a variable (newmm) that will no longer exist when control is passed back to the calling statement.
    To fix this, make newmm a pointer variable and then use the new method to create a Quant object. Then return the pointer variable itself, which is just the address of the new object in memory.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s