Hello I have four files: AllOnesGA.cpp, GeneticAlgorithm.h, Population.h, Individual.h
And I don't know why individual.getFitness() give me -1 and not 2 that is the last value that I give it with the method setFitness
Thank you very much
In main...AllOnesGA.cpp
1 2 3 4 5 6 7
int main()
{
GeneticAlgorithm ga(100);
Population population = ga.initPopulation(50);
ga.evalPopulation(population);
ga.isTerminationConditionMet(population);
...
This makes no sense at all. This gives you a COPY of a single Individual? Anything you do to that copy will be lost. population should be a container (for example, vector<Individual> ) and the loop would look like this:
1 2 3 4
for (Individual& individual : population)
{
individual.setFitness(2);
}
You have a class, I'm guessing of type Population.
Classes should take responsibility for themselves. They should not be handing out parts of themselves to other objects so that those objects can alter them. This breaks encapsulation. It's just bad design for something so simple.
If the Population object needs to change, it should have a class function that does the change, and you should call that function.
I know the difference in passing by value or by reference in a method
but I don't know enought c++ to trnslate thisk chunk of code in Java to c++
thanks
Sounds about right. Java tends to pass by reference, by default. C++ by value.
You think you're passing by reference in your code; you're not.
You think you're passing around a single object; you're not, you're making copies, changing them, and then throwing them away, leaving the original unchanged.
If you come back to C++, learn about pass-by-value and pass-by-reference.