Giuseppe Giuseppe - 1 month ago 21
C++ Question

undefined reference to c++ error

Hi guyys i need your help!
When i compile run time error is :

/tmp/ccSOgpjn.o: In function

Collection::evaluate()':
fitnessTest.cpp:(.text._ZN10Collection8evaluateEv[_ZN10Collection8evaluateEv]+0x45): undefined reference to
fitnessFunction::doEvaluation(std::__cxx11::basic_string, std::allocator >)'
/tmp/ccSOgpjn.o: In function
Collection::writeIndividual(char**, int)':
fitnessTest.cpp:(.text._ZN10Collection15writeIndividualEPPci[_ZN10Collection15writeIndividualEPPci]+0x3a): undefined reference to
readIndividual::read[abi:cxx11](char**, int)'
collect2: error: ld returned 1 exit status

I can not understand why?

my code is :



class fitnessFunction
{
public:
virtual int doEvaluation(string x);

};

class OneMax: public fitnessFunction
{
public:
virtual int doEvaluation(string x) {
int count = 0;
for (int i = 0; i < x.size(); i++)
if (x[i] == '1') count = count + 1;
return count;
}


};



class readIndividual
{
public:
string read(char * argv[], int i);

};

class OneMaxIndividual: public readIndividual
{
public:
virtual string read(char * argv[], int i) {
string inputFile = argv[i+1];
ifstream input(inputFile.c_str());
string x;
input >> x;
input.close();
return x;
}


};



class Collection
{
public:
fitnessFunction* m_function;
readIndividual* m_individual;
string individual;
public:
Collection(){}
void set_function(fitnessFunction* s){
m_function = s;
}
void set_individual(readIndividual* s){
m_individual = s;
}
int evaluate() {
m_function->doEvaluation(individual);
}
void writeIndividual(char* argv[], int i) {

individual = m_individual->read(argv,i);
}


};



int main(int argc, char* argv[])
{

int result = 0;
string outputFile = "fitness.out";
ofstream output( outputFile.c_str() );

OneMax fitnessFunction;
OneMaxIndividual individualObj;

Collection collection;
collection.set_function(&fitnessFunction);
collection.set_individual(&individualObj);

for(int i = 0; i < argc/2; i++){
//lettura individo
collection.writeIndividual(argv,i);
result = collection.evaluate();
output << result << endl;
}

for(int i = argc/2; i < argc-1; i++){


collection.writeIndividual(argv,i);
result = collection.evaluate();
output << result << endl;

}

output.close();

return 0;
}


I tried a few more questions like mine but have not found answers that I have solved the problem. The above code in all in a one page.

Answer

your doEvaluation(string ) function in fitnessFunction class has no implementation.

you have two options: - make it pure virtual by appending =0 at the end or - create dummy implementation

I sugest to make it pure virtual so that you are forced by the compiler to create implementation in derivated classes.