undefined reference to c++ error [duplicate] - c++

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 6 years ago.
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 tofitnessFunction::doEvaluation(std::__cxx11::basic_string, std::allocator >)'
/tmp/ccSOgpjn.o: In function Collection::writeIndividual(char**, int)':
fitnessTest.cpp:(.text._ZN10Collection15writeIndividualEPPci[_ZN10Collection15writeIndividualEPPci]+0x3a): undefined reference toreadIndividual::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.

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.

Related

LNK2019: unresolved external symbol _WinMain#16 referenced in function "int __cdecl invoke_main(void)" (?invoke_main##YAHXZ) [duplicate]

This question already has answers here:
c++ class why need main?
(5 answers)
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 1 year ago.
I'm new to c++ and I just don't get this error on visual studio community. I already tried so many things like changing properties settings. Like configuration Type. Also the Subsystem from Console to Windows Rewriting it. At this point I just really need help.
So this is my Header file.
#include <iostream>
#include<string>
using namespace std;
#ifndef University_h
#define University_h
class University
{
public:
University();
void setUniversityID(int);
int getUniversityID();
void setCourseIdSectId(int, int);
string getCourseIdSectId();
void setCredits(int);
int getCredits();
void setDaysTime(int, string);
string getDaysTime();
void setRoomID(int, int);
string getRoomID();
void setMaxallotment(int);
int getMaxallotment();
void setCampus(string);
string getCampus();
void setCourseInstructor(string);
string getCourseInstructor();
void setEnrollStudents(int);
int getEnrollStudents();
void setCourseStatus(string);
string getStatus();
private:
int universityIDNumber;
int DeptID;
int sectID;
int noOfCredits;
int days;
string time;
int buildingID;
int roomID;
int maxEnrollment;
string courseCampus;
string courseInstructor;
int noOfStudentsEnrolled;
string courseStatus;
};
#endif
And this is my main.cpp
#include "University.h"
University::University()
{
universityIDNumber = 0;
DeptID = 0;
sectID = 0;
noOfCredits = 0;
days = 0;
time = "00:00";
buildingID = 0;;
roomID = 0;
maxEnrollment = 0;
courseCampus = "unknown";
}
void University::setUniversityID(int ID)
{
universityIDNumber = ID;
}
int University::getUniversityID()
{
return universityIDNumber;
}
void University::setCourseIdSectId(int deptId, int sId)
{
DeptID = deptId;
sectID = sId;
}
string University::getCourseIdSectId()
{
return DeptID + " " + sectID;
}
void University::setCredits(int credits)
{
noOfCredits = credits;
}
int University::getCredits()
{
return noOfCredits;
}
void University::setDaysTime(int ds, string tm)
{
days = ds;
time = tm;
}
string University::getDaysTime()
{
return days + " " + time;
}
void University::setRoomID(int buildId, int roomid)
{
buildingID = buildId;
roomID = roomid;
}
string University::getRoomID()
{
return buildingID + " " + roomID;
}
void University::setMaxallotment(int maxNums)
{
maxEnrollment = maxNums;
}
int University::getMaxallotment()
{
return maxEnrollment;
}
void University::setCampus(string campusName)
{
courseCampus = campusName;
}
string University::getCampus()
{
return courseCampus;
}
void University::setCourseInstructor(string name)
{
courseInstructor = name;
}
string University::getCourseInstructor()
{
return courseInstructor;
}
void University::setEnrollStudents(int enrollment)
{
noOfStudentsEnrolled = enrollment;
}
int University::getEnrollStudents()
{
return noOfStudentsEnrolled;
}
void University::setCourseStatus(string status)
{
courseStatus = status;
}
string University::getStatus()
{
return courseStatus;
}
Do you remember any lectures (or sections in your text-book) telling you that all C++ programs must have a main function?
Well for Windows GUI programs this is called WinMain instead.
Unless you want a Windows GUI program you should make sure that you create a console type project in Visual Studio, and use the existing templates so Visual Studio creates a main function for you.

problem passing array of struct to a function throwing undefined reference c++

I'm having issues with passing an array of structures to a function that searches them. I delcare an array of structs outside of main then copy it to a new array of structs inside of main (so I have access to them inside main and can pass them easier). Not sure why it is failing though. Can anyone help me?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <algorithm>
using namespace std;
const int MAX = 2000000;
const string DFile = "DFile.dms";
const string EFile = "EFile.dms";
const string VFile = "VFile.dms";
struct dogs
{
int did;
int age;
} DFBuffer[MAX];
struct examine
{
int vid;
int did;
int fee;
} EFBuffer[MAX];
struct vet
{
int vid;
int eLevel;
} VFBuffer[MAX];
void readDF(ifstream&);
void readEF(ifstream&);
void readVF(ifstream&);
int getLineCount(ifstream&);
bool dogCompare(dogs lhs, dogs rhs) {return lhs.did < rhs.did;}
bool vetCompare(vet lhs, vet rhs) {return lhs.vid < rhs.vid;}
bool examCompare(examine lhs, examine rhs) {return lhs.vid < rhs.vid;}
void vetExamSeach(struct vet newVetArray[], struct examine newExamArray[],
int, int);
int main()
{
dogs * newDogArray = new dogs[MAX];
examine * newExamArray = new examine[MAX];
vet * newVetArray = new vet[MAX];
ifstream DF, EF, VF;
int dogCount = 0, examCount = 0, vetCount = 0;
DF.open(DFile);
readDF(DF);
EF.open(EFile);
readEF(EF);
VF.open(VFile);
readVF(VF);
DF.open(DFile);
dogCount = getLineCount(DF);
EF.open(EFile);
examCount = getLineCount(EF);
VF.open(VFile);
vetCount = getLineCount(VF);
for(int i = 0; i < dogCount; i++)
newDogArray[i] = DFBuffer[i];
for(int i = 0; i < vetCount; i++)
newVetArray[i] = VFBuffer[i];
for(int i = 0; i < examCount; i++)
newExamArray[i] = EFBuffer[i];
cout << "Sorting...\n";
sort(newDogArray, newDogArray + dogCount, dogCompare);
sort(newExamArray, newExamArray + examCount, examCompare);
sort(newVetArray, newVetArray + vetCount, vetCompare);
cout << "Sorting complete!\n";
vetExamSeach(newVetArray, newExamArray, vetCount, examCount);
return 0;
}
here is the search function. for the sake of this question, im just trying to print what i pass it.
void search(vet newVetArray[], examine newExamArray[], int vCount, int eCount)
{
for(int i = 1; i < vCount; i++)
cout << "in search: " << newVetArray[i].vid << ' ' << newVetArray[i].eLevel << endl;
}
here is the error I'm getting
Here is my files. Not asking you to do my HW just help me solve my issue
When, I run your code, I get the same compilation error of undefined reference for readDf, readEF, readVF, getLineCount and vetExamSeach.
The error is because there is no definition of these functions. There are only just decalarations. When I define them (something random) the errors are gone.
So, define the function(s) and the error(s) would be gone.

Virtual function is not getting overridden [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I can't figure out why my virtual function is not being overridden, when looking up examples online I can't spot what I'm doing wrong, I must be missing something.
Base Class
class HashTable {
// removed some unrelated functions and data to keep this page short
void Insert(int key, HashTable *htable)
{
int pos = Find(key, htable);
if (htable->table[pos].info != Legitimate)
{
htable->table[pos].info = Legitimate;
int rKey = Reverse(key);
htable->table[pos].element = rKey;
}
}
virtual int Find(int key, HashTable *htable)
{
return 0;
}
};
Children Class
class SingleHash : public HashTable {
int Find(int key, HashTable *htable)
{
int hashVal = HashFunc1(key, htable->size);
while (htable->table[hashVal].info != Empty &&
htable->table[hashVal].element != key)
{
hashVal = hashVal;
hashVal = hashVal % htable->size;
prob = prob + 1;
}
trackProbes(prob);
return hashVal;
}
};
class DoubleHash : public HashTable {
int Find(int key, HashTable *htable)
{
int hashVal = HashFunc1(key, htable->size);
int stepSize = HashFunc2(key, htable->size);
while (htable->table[hashVal].info != Empty &&
htable->table[hashVal].element != key)
{
hashVal = hashVal + stepSize;
hashVal = hashVal % htable->size;
prob = prob + 1;
}
trackProbes(prob);
return hashVal;
}
};
What my main is looking like
int main()
{
int value, size, pos, i = 1;
int choice = 1;
HashTable *htable = new SingleHash;
cin >> value;
htable->Insert(value, htable);
// more unrelated stuff
}
When I run my program it just returns what's in the base class (0) when I make a call to Insert.
There are compile errors in code you provided like functions your not declared public for basics.
I tried to make MCVE for you, and it seems to be working fine.
#include <iostream>
using namespace std;
class HashTable {
public:
void Insert(int x) {
Find(x);
}
virtual int Find(int x) {
cout<<"base hash find \n";
return x; }
};
class SingleHash : public HashTable {
public:
int Find(int x) {
cout<<"single hash find \n";
return x*2;
}
};
class DoubleHash : public HashTable {
public:
int Find(int x) {
cout<<"DOuble hash find \n";
return x*3; }
};
int main(int argc, char** argv)
{
int value;
HashTable *hsingle = new SingleHash;
cin >> value;
hsingle->Insert(value);
HashTable *hdouble = new DoubleHash;
hdouble->Insert(value);
return 0;
}
The output is :
single hash find
DOuble hash find

How to initialize a constant in a class? [duplicate]

This question already has answers here:
How to initialize const member variable in a class?
(11 answers)
Closed 7 years ago.
So I've looked around and nothing I found has helped me so far.
I have the following header file for my class.
#ifndef CONGERA2_H
#define CONGERA2_H
typedef float Element300;
class Stack300
{
public:
Stack300 ();
Stack300 (const int);
Stack300 (Stack300 &old);
~Stack300();
void push300(const Element300);
Element300 pop300();
void viewTB300();
void viewBT300();
private:
const int MAX_STACK;
Element300 * stackArray;
int top;
};
#endif
And I'm trying to initialize MAX_STACK. If I set it equal to something I get a warning, which would normally be fine but I must transfer this code to Linux afterwards and I can't do that because it says that MAX_STACK is undefined in my three constructors. I've also tried defining it in my class functions file in the first constructor but then I get an error saying that MAX_STACK is not defined in the constructor.
Here is the constructors for my class functions if they are needed.
#include <iostream>
#include "congera2.h"
using namespace std;
Stack300::Stack300 (): MAX_STACK(10)
{
stackArray = new float[3];
for (int i = 0; i < 3; i++)
{
stackArray[i] = '\0';
}
top = -1;
return;
}
Stack300::Stack300 (const int size) : MAX_STACK (10)
{
stackArray = new float[MAX_STACK];
for (int i = 0; i < MAX_STACK; i++)
{
stackArray[i] = '\0';
}
top = -1;
return;
}
Stack300::Stack300 (Stack300 &old) : MAX_STACK (10)
{
top = old.top;
int i = 0;
while (top != old.top)
{
stackArray[i] = old.stackArray[i];
i = i + 1;
top = i;
}
}
Error:
class A
{
public:
const int x=8; // error (c++98/03)
};
Fix 1
class A
{
public:
const int x;
A() : x(8) // ok
{ }
};
Fix 2
class A
{
public:
const static int x;
};
const int A::x=8; // ok

Getting crash while calling a function which need reference to vector

I want to know is there something wrong in passing in passing vector reference to a function as in the example below. This code is running well and nice. But the same type of code in my project gives me crash. I don't know why.
In that case whenever I calls the function which need std::vector & . then in the called function the size of the vector reaches some millionsss.... I have attached screenshot where I am actually getting this crash.
I just wants to know is there something wrong in these type of implementations...
#include <iostream>
#include <vector>
#include <string>
class A {
public:
A() {}
~A() {}
void GetVector(std::vector<std::wstring> &in) {
std::wstring s = L"Hello";
for(int i = 0; i < 10; i++)
in.push_back(s);
}
};
class B {
public:
B() {}
~B() {}
void GetData() {
A a;
std::vector<std::wstring> s;
a.GetVector(s);
}
};
int main() {
B b;
b.GetData();
return 0;
}
Real code where I am getting the crash...
void SCPreferenceComp::PopulateComboBox()
{
SCConfig *config = SCConfig::GetInstance();
std::vector<std::wstring> languages;
config->GetAllLangugesName(languages);
for(size_t i = 0; i != languages.size(); i++)
mLangListComboBox->addItem(languages[i].c_str(), i+1);
if(mLangListComboBox->getNumItems() > 0)
mLangListComboBox->setSelectedId(1);
}
bool SCConfig::GetAllLangugesName(std::vector<std::wstring> &outLangNames)
{
bool retVal = false;
do
{
if(!mXMLDoc)
break;
xercesc::DOMNodeList *langNodeList = mXMLDoc->getElementsByTagName(strToX("language"));
if(!langNodeList)
break;
const XMLSize_t langCount = langNodeList->getLength();
for(XMLSize_t i = 0; i < langCount; i++)
{
xercesc::DOMNode *curLangNode = langNodeList->item(i);
if(!curLangNode)
continue;
xercesc::DOMElement *curLangElem = dynamic_cast<xercesc::DOMElement*>(curLangNode);
if(!curLangElem)
continue;
wxString s = strToW(curLangElem->getAttribute(strToX("name")));
outLangNames.push_back(s.c_str());
}
retVal = true;
}while(false);
return retVal;
}
I can't see anything wrong in that implementation other than the fact that it doesn't have any visible end result which leads me to believe it may not exactly match your failing code.