0

Why doesn't my code work?

Hi everyone! I created this c++ code and separated the header and the source files but it doesn't work. I keep receiving this error: ||=== Build: Debug in composition (compiler: GNU GCC Compiler) ===| obj\Debug\main.o||In function `main':| D:\coding files\C++\CodeBlocks\composition seperate files\main.cpp|8|undefined reference to `name::name(std::string)'| D:\coding files\C++\CodeBlocks\composition seperate files\main.cpp|10|undefined reference to `name::print_name()'| ||error: ld returned 1 exit status| ||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===| Take a look at my code: main.cpp ------------------------- #include <iostream> #include <string> #include "name.h" using namespace std; int main() { name obj("John"); obj.print_name(); return 0; } ---------------- name.h ---------------- #ifndef NAME_H #define NAME_H #include <iostream> #include <string> using namespace std; class name { public: name(string n); void print_name(); private: string name_str; }; #endif // NAME_H ------------------------ name.cpp ------------------------ #include "name.h" #include <iostream> #include <string> using namespace std; name::name():name_str(n){} void name::print_name() { cout<<"name: "<<name_str<<endl; }

11th Sep 2018, 11:35 AM
H2727
H2727 - avatar
3 Answers
+ 5
In name.cpp's constructor, n is undefined You probably want something like name::name(std::string n):name_str(n) {}
11th Sep 2018, 11:43 AM
jay
jay - avatar
+ 4
I will have a proper look when I get home :) that was just the first thing that jumped out at me
12th Sep 2018, 7:00 AM
jay
jay - avatar
+ 1
Thanks but it still doesn't work
12th Sep 2018, 5:45 AM
H2727
H2727 - avatar