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

C ++ is new here! There is a class Individualthat highlights a lot of memories, so we want to avoid copying. Let motherand fatherbe two Individuals. I would like them to reproduce using a method reproduceto make another one Individualcalled baby.

Intuitively, I would initialize babywith the default constructor, pass it in an argument reproduceand return the link (although, I suppose, there is no need to return the link). Here is the code that does this

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 a good practice?

baby reproduce , , baby reproduce, .

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);
}

, , .

+4
3

- reproduce .

, ; , , , ; , , , !

; Individual ( ), -. , .

undefined, . .

+6

Individual , Individual, :

class Individual
{
public:
    Individual(Individual const& mother, Individual const& father)
    {
        // Pass on traits.
    }
};

, , reproduction , .

+1

:

- , , .

, , .

, ( IMHO), . , , reproduce , ( ). p >

, ?

Individual baby;
mother.reproduce(father,baby);
if (baby.exists()) {
   // do stuff
}

, , , . , ( ), .

Individual* reproduce (Individual *father)
...
Individual *baby = mother->reproduce(father);
if (baby != nullptr) {
    // do stuff
}

bool reproduce (Individual *father, Individual * &baby) // or **baby
...
Individual *baby = nullptr;
if (mother->reproduce(father, baby) {
    // do stuff
}

- ( , , , ). . ( ), , "".

, "" .

P.S. , .

+1

Source: https://habr.com/ru/post/1657438/


All Articles