3

Let's say I have three files A.cpp, B.cpp, and B.h. A.cpp and B.cpp both include B.h. I defined a free function in B.h (for whatever reasons). Then I get a linker error:

ld: 1 duplicate symbol for architecture x86_64

Which makes sense. The compiler compiles A.cpp and B.cpp separately, and so there are two functions with the same name and parameters.

However, if I declare a class in B.h and define a member-function in this class, it compiles just fine. Why is that? Shouldn't that create the same linker error?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jiddoo
  • 1,091
  • 2
  • 9
  • 14
  • 4
    Does this answer your question? [Basic ODR violation: member functions in .h files](https://stackoverflow.com/questions/66528686/basic-odr-violation-member-functions-in-h-files) – François Andrieux Apr 27 '21 at 15:54
  • 1
    I am no expert in linking but it might be that the simple answer is because member functions are implicitly `inline`. Try adding `inline` to your free function and see. – alfC Apr 27 '21 at 15:54

1 Answers1

7

Why is it ok in C++ to define a member function in a header but not a free function?

It is not OK to define non-inline functions more than once. This is part of the "One Definition Rule".

It is OK to define inline functions in more than one translation unit. In fact, inline functions must be defined in every translation unit where they are used.

Header files are typically included into multiple translation unit. Therefore all functions defined in a header should be inline functions.

Member functions that are defined within the class definition are implicitly inline. Being inline functions, it is OK to define them in a header, just as it is OK to define inline non-member functions in a header. Similarly, it is not OK to define non-inline member functions in a header just like it isn't OK to define non-inline non-member functions in a header.

eerorika
  • 232,697
  • 12
  • 197
  • 326