There was a problem when writing a template class, in its test method a method of another class is called, I get an error when compiling

undefined reference to `bar :: printHello () '

What could be the problem?

main.cpp

#include<main.h> #include <foo.h> int main(){ foo<int> _fo ; _fo.test(); return 0; } 

main.h

 #pragma once #include <bar.h> 

foo.h

 #pragma once #include<bar.h> template<class T> class foo{ public: foo(){ } void test(){ bar b; b.printHello(); } }; 

foo.cpp

 #include "foo.h" 

bar.h

 #pragma once class bar { public: bar(); void printHello(); }; 

bar.cpp

 #include "bar.h" #include <iostream> bar::bar() { } void printHello(){ std::cout<<"Hello"; } 
  • Look here . - αλεχολυτ

1 answer 1

You did not try to rewrite

 void printHello(){ std::cout<<"Hello"; } 

as

 void bar::printHello(){ std::cout<<"Hello"; } 

?
Those. clarify that this is not just a free function printHello , but a member of the class bar ?

  • I tried, I got extra qualification 'bar::' on member 'printHello' which, in my opinion, is logical, because she’s in the public of this class, which clearly indicates that she is his member. - Ivan Morozoboev
  • Where did you write this? In bar.cpp ? Either printHello definition of printHello to the bar declaration, or in the definition of printHello add which class it belongs to. - Harry
  • Blunted, wrote in bar.h, added void bar :: printHello () in bar.cpp and the problem was solved, thank you. - Ivan Morozoboev