I have been following a C++ course on Udemy. However, they do not seem to separate classes (ie: they keep all classes in the main.cpp file). I wanted to try to separate classes for a personal project.
I have a class "Prefecture". I split it into "Prefecture.h" and "Prefecture.cpp" as I have seen online.
Prefecture.h:
#include <string>
#include <vector>
#include <utility>
// user defined classes
using namespace std;
#pragma once
class Prefecture{
private:
string _name;
string _capital;
string _region;
double _area;
string _island;
// data for yearly pop change
vector<pair<double,double>> _pairVec;
public:
Prefecture(string aName);
void pushToPairVec(double aYear, double aPop);
// setters
void setName(string aName);
// getters
string getName();
vector<pair<double,double>> getPairVec();
};
Prefecture.cpp:
#include <utility>
#include <string>
#include "Prefecture.h"
using namespace std;
Prefecture::Prefecture(string aName){
_name = aName;
}
void Prefecture::setName(string aName){
_name = aName;
}
string Prefecture::getName(){
return _name;
}
vector<pair<double,double>> Prefecture:: getPairVec(){
return _pairVec;
}
void Prefecture::pushToPairVec(double aYear, double aPop){
_pairVec.push_back(pair(aYear,aPop));
}
Note that my outside classes are in a folder "classes". Thus to get to the header file I do ./classes/Prefecture.h , and for the cpp I do ./classes/Prefecture.cpp
Here is my main.cpp:
#include <iostream>
#include <string>
#include <vector>
#include "./classes/Prefecture.h"
using namespace std;
int main(int argc, char const *argv[])
{
Prefecture g("hello");
cout << g.getName() << endl;
return 0;
}
When I run this in VSCode, the following error occurs:
C:\Users\whale\AppData\Local\Temp\ccMIrBlR.o:main.cpp:(.text+0x55): undefined reference to `Prefecture::Prefecture(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
C:\Users\whale\AppData\Local\Temp\ccMIrBlR.o:main.cpp:(.text+0x7d): undefined reference to `Prefecture::getName[abi:cxx11]()'
collect2.exe: error: ld returned 1 exit status
PS D:\Desktop\cppData>
I am not sure how to fix this.