Home Segments Index Top Previous Next

708: Sidetrip

C++ does not prevent you from defining member functions in class definitions provided in header files. At first, such member-function definitions may seem to violate the principle that functions are to be defined only once, because header files are likely to be included in multiple source files.

Nevertheless, you can get away with such definitions, because the developers of C++ have gone to considerable trouble to make such definitions possible, albeit not preferred.

First, your C++ compiler tries to compile the member functions defined inside a class definition as inline functions.

Recall that, each time an ordinary function appears, the C++ compiler arranges for the calling function to suspend what it is doing. Then, the program assigns parameters to arguments, jumps to the body of the called function, returns a value from that called function, and resumes where it left off in the calling function.

In contrast, each time an inline function appears, the C++ compiler substitutes the body of the function at that place. There is no subsequent function call, with parameter assignment and value returning; instead, the body of the inline function becomes part of the body of the calling function.

Accordingly, when an inline function appears, the C++ compiler needs only to prepare to substitute its body into places where the function is called; no program memory is allocated for the function at the time the function definition appears. Thus, an inline function definition actually is more like a declaration than an ordinary definition.