I'm working through the C++ Primer (5th Edition), and while it's been really great material so far, I find in some instances I run into head-scratching explanations that give me more questions than answers.
In the current example (emphasis mine on the bolded):
Unlike other functions, inline and constexpr functions may be defined multiple times in the program. After all, the compiler needs the definition, not just the declaration, in order to expand the code. However, all of the definitions of a given inline or constexpr must match exactly. As a result, inline and constexpr functions normally are defined in headers.
I've done a bit of research on this, and I've seen many answers that I'm able to define an inline function multiple times as long as the definition is identical. Additionally, I've seen that the standard allows for this. What I'm curious is: why?
Is there a feasible coding situation where I would have my #include for a given header file for an inline function I want, only to provide a duplicate definition in my .cpp file? I feel like I'm missing an obvious situation where this rule is applicable. Why not just make it so you could only define the inline function once in the header, period, and not worry about it afterwards?
All the best.
The answer is surprisingly straightforward: this is done to allow you define the body of inline functions inside header files.
Since header files are "pasted" verbatim inside a translation unit that references them, any function definitions inside the headers would end up inside that translation unit. If you include the same header from several files, all these files would have defined the same function, with identical definitions (because they come from the same header).
Since the preprocessing stage is done before compiling, the compiler has no idea what part of a translation unit came from a header, and which was there in your cpp file. That's why it was easier for standard writers to allow multiple identical definitions.
Why not just make it so you could only define the inline function once in the header, period, and not worry about it afterwards?
Reasons that I can think of.
The compiler won't be able to enforce it. The contents that it processes are already pre-processed.
Also, mandating that inline functions be defined only in header files is too restrictive. You will find a large number of classes defined only in source files in real world applications. It will be a shame if those classes couldn't use inline
functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With