member functions and inline

Hello, I am learning about inline functions and I was hoping someone could clarify something for me. The book I am learning from says that all functions declared within the class definition are automatically inline. But so far the book has not went over header files, but I know they exist. I just want to double check, that if the function is prototyped in the header file inside the class definition, but the code for the function is in the cpp file, this will not make the function inline. And it is only when the function declaration itself is between the curly braces of the class declaration that it is inline. Thanks for any help
A tutorial about header files:
https://www.learncpp.com/cpp-tutorial/header-files/

I recommend also reading the next lesson about Header Guards:
https://www.learncpp.com/cpp-tutorial/header-guards/

Defining a class in a header file:
https://www.learncpp.com/cpp-tutorial/89-class-code-and-header-files/
Last edited on
There are 2 ways to inline a function. The first is to declare it within the class definition. The second is to declare it inline later in the header file.*

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyClass
{
public
    MyClass::MyClass() : x(5), y(10) {}   // inline constructor
    int getX() { return x; }              // inline function defined inside class def.
    int getY();

private:
    int x;
    int y;
};

inline int MyClass::getY() { return y; }      // inline function defined outside of class def. 



(*) When you get more advanced, you might learn that you can define inline function, usually file-scope, inside a source file. But 99% of the time they will be inline class member functions, and they ALL go in the header file.
Last edited on
If the member function is declared inside the class and then defined later on, then the definition is not inline, unless, of course, you specifically say it should be inline.

Put another way, code is inline if (1) you specifically say it should be with the "inline" keyword, or (2) you define the code of a member function inside the function declaration.

Header files actually have nothing to do with this. When you say #include "foo.h" it basically tells the compiler to paste a copy of foo.h into that spot of the program. Whether you put a class declaration in a header file or in a code file has no bearing on what gets inline treatment.

One more thing to keep in mind: making a function inline is only a hint. The compiler may decide to put the function out-of-line if it chooses. There should be no difference in functionality.
Topic archived. No new replies allowed.