Link to home
Start Free TrialLog in
Avatar of ambuli
ambuliFlag for United States of America

asked on

Returning an Object in a function

Hi Experts,

I have the following.  In getB( ) function when I return the Object b, would I have any problems.  I think If I do " B b = new B( ); " and returning &b would cause problem as the function returns, b goes out of scope.  Is it true even in my case?
 

class A
{

};

class B
{

};

class C
{
public:
     C( A& aa);
     B& getB( );  
private:
    A * m_aa;
};

B& C::getB( )
{
     B b;
    //do some initialization of B here
    return b;
}
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oh, and you are right

B* C::getB( )
{
     B* b = new B;
    //do some initialization of B here
    return b;
}

would also be an option, yet that would require more attention about deleting the objects. Also

B& C::getB( )
{
     B b;
    //do some initialization of B here
    return b;
}

will *not* work, since the reference returned would be invalid as soon as the function exits.