Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to give an empty instance to a method?

C++ newbie here! There is a class Individual which allocates a lot of memories so that we want to avoid having to copy. Let mother and father be two Individuals. I would like them to reproduce with the method reproduce to make another Individual called baby.

Intuitively, I would initialize baby with the default constructor, pass it in argument to reproduce and return the reference (although I suppose it is not necessary to return the reference). Here is a code that does that

class Individual
{
    public:
        void reproduce (const Individual& father, Individual& baby)
        {
          // Set all attributes of baby
        }
    private:
        // Plenty of variables
}

int main()
{
  // Do Stuff
    Individual mother(arg1,arg2,arg3);
    Individual father(arg1,arg2,arg3);
    // Do stuff
    Individual baby;
    mother.reproduce(father,baby);
}

Is this considered good practice?

Another way would be to initialize baby directly in the method reproduce and return a reference but I would predict that the baby would be destroyed at the end of the call of reproduce though.

class Individual
{
    public:
        Individual& reproduce (const Individual& father)
        {
            Individual baby;
        // Set all attributes of baby
        return baby
        }
    private:
        // Plenty of variables
}

int main()
{
  // Do Stuff
    Individual mother(arg1,arg2,arg3);
    Individual father(arg1,arg2,arg3);
    // Do stuff
    auto baby = mother.reproduce(father);
}

One could as well use an external function but I don't see what advantage that could represent.

like image 254
Remi.b Avatar asked Feb 06 '23 22:02

Remi.b


1 Answers

The member function reproduce should return the baby.

It makes no sense to have a baby beforehand that's merely altered by the act of reproduction — this would be more akin to your parents finding the baby on the doorstep, having been deposited by a stork, then moulding the baby into their family; hopefully you know by now that this is not how it works!

Don't worry about performance; if your Individual class has a move constructor (or follows the rule of zero) then this is a complete non-issue. Even if not, Return Value Optimisation should take care of things anyway.

Your attempt to return a reference to a local variable has undefined behaviour, as you correctly intuited. So don't do this.

like image 157
Lightness Races in Orbit Avatar answered Feb 08 '23 17:02

Lightness Races in Orbit