It's because you defined MyClass::foo
in a header file. Or a bit more abstract, that definition will be present in multiple translation units (every .cpp file that includes the header).
Having more than one definition of a variable/function in a program is a violation of the one definition rule, which requires that there must be only one definition in a single program of every variable/function.
Note that header guards do not protect against this, as they only protect if you include the same header multiple times in the same file.
Marking the function definition as inline
though means that the definition will always be the same across multiple translation units.1.
In practice, this means that the linker will just use the first definition of MyClass::foo
and use that everywhere, while ignoring the rest,
1: If this is not the case your program is ill-formed with no diagnostics required whatsoever.
foo
were not part of the class, would you understand why you would have to mark its definitioninline
? Because the same reasoning applies here as well. – Inclementfoo
in the header and since that header can be included in more sources, you must tell the compiler to inform the linker about the definition duplicates, so that they can be merged. Is that correct? – Fadinline
is a request, not a guarantee, see: en.cppreference.com/w/cpp/language/inline – Magnetographinline
the function definition since technically the header file would be include only once in that case? – Fad