PDA

View Full Version : problem with virtual function in a .h



mickey
19th April 2008, 17:14
Hello,
I attach you the class; It works now but I want understand where exactly is the origin of the problem...
If I do the same thing inside a .cpp, the "inline" keyword isn't necessary; then, I don't understand the compiler message (.net) ("already defined in main.obj")


error LNK2005: "public: virtual struct Tree::Node * __thiscall Tree::getRoot(void)const " (?getRoot@Tree@@UBEPAUNode@1@XZ) already defined in main.obj


Thanks

wysota
19th April 2008, 17:17
If you omit the inline keyword and include the header file in more than one other files that get compiled, you'll get two or more definitions of the same function and that is forbidden. Either make the function inline or put it into a .cpp file.

mickey
19th April 2008, 18:42
I still don't understand; maybe could you me get some page on thinking in c++ where read it?
I have #include "tree.h" in main.cpp and in tree.cpp; but in .h, I used the keyword "#ifndef ..., #define....., #endif ". Shoulnd't be this enough to prevent that error?

wysota
19th April 2008, 18:49
No, because defines are only relevant inside current compilation unit thus define guardians are not enough.

mickey
19th April 2008, 18:50
No, because defines are only relevant inside current compilation unit thus define guardians are not enough.
But in my case, isn't "the unit compilation unit" the .h file????

wysota
19th April 2008, 18:57
No. header files are included into compilation units. A single compilation unit is a cpp with all included files. You get object files out of implementation files not header files. In your case the definition of the getRoot() method is present in two separate objects and when the linker links them together, it gets confused. Simply move the body of the method to some cpp file that includes your header file and everything will be fine. Just be sure to leave the declaration of the method in the header or you won't be able to use it from within other units.