-3

Why can't this work? toBeEvolved is a std::vector, .getIndividual returns an element

Individual& EvolutionaryAlgorithm::tournamentSelection(unsigned int i)
{
    return toBeEvolved.getIndividual(i);
}

Individual* in2 = tournamentSelection(0);

Compile Time Error: No viable conversion from 'Individual' to 'Individual*'

1 Answers1

1

You need to take the address of the reference in order to convert it to a pointer. Even though you may know that the reference is handled as a pointer by the compiler "behind the scenes", there is no explicit requirement in the language that references be implemented as pointer variables, and you will still need to use an explicit & operator to tell it you want the address as a pointer. So:

Individual* in2 = &tournamentSelection(0);

Other posters have gone into much greater depth on the distinction between pointers and references.

Community
  • 1
  • 1
Jeffrey Hantin
  • 35,734
  • 7
  • 75
  • 94