I'm creating an object in main.cpp like this:
#include <string>
#include "class.hpp"
std::string param = "name";
int main(){
Class object(param);
}
class.cpp:
#include <string>
class Class {
public:
std::string name;
Class(std::string name) {
this->name = name;
}
};
class.hpp:
#pragma once
class Class {
public:
std::string name;
Class(std::string name);
};
However, when doing this I receive:
undefined reference to `Class::Class(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)'
BUT if I put the constructor implementation in the header like this:
#pragma once
class Class {
public:
std::string name;
Class(std::string name) {
this->name = name;
}
};
It works. But now my hpp and cpp files are identical except for the include statement I have at the top of class.cpp.
My question is, is this bad practice? It seems redundant and wrong. What am I missing here? Why do I need to put the implementation for a constructor in the header?