Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to define inline functions?

Tags:

c++

inline

Say I have a class X (X.h):

class X {
  private:
    unsigned unitsSold = 0;
    double revenue = 0.0;

  public:
    double avgPrice();
}

Which way should avgPrice() be defined?

Option 1 (in-class):

X.h

class X {
  private:
    unsigned unitsSold = 0;
    double revenue = 0.0;

  public:
    double avgPrice() {
      return unitsSold ? revenue / unitsSold : 0;
    }
}

Option 2 (in same file as the class, but outside of the class definition):

X.h

class X {
  private:
    unsigned unitsSold = 0;
    double revenue = 0.0;

  public:
    double avgPrice();
}

inline double X::avgPrice() {
  return unitsSold ? revenue / unitsSold : 0;
}

or Option 3 (in a seperate header file):

X.h:

class X {
  private:
    unsigned unitsSold = 0;
    double revenue = 0.0;

  public:
    double avgPrice();
}

X-inl.h:

#include "X.h"

inline double X::avgPrice() {
  return unitsSold ? revenue / unitsSold : 0;
}
like image 797
Timo Türschmann Avatar asked Mar 22 '23 19:03

Timo Türschmann


1 Answers

There might be some misunderstanding about the meaning of inline specifier. Yes, it does give a hint to the compiler that it would be preferred to inline the code instead of making a call, but compiler is not forced to obey this hint. The main use of inline specifier is to avoid violations of One Definition Rule.

Once you declare a function inline, it needs to be defined in every translation unit it used and the definition must be exactly the same every time. It is the other way around than as your title suggests - the choice of where you define the function mandates whether it needs to be marked inline or not.

1) and 2) are okay. In the first case it is implicitly inline and in the second you explicitly declared it so. The definition is the same wherever you include the header.

Case 3) will only work if you compile and link X_impl.h as a source file. In that case there will be only one definition and inline would be redundant. This way the compiler doesn't see the definition in other translation units, though, and that makes it impossible for it to inline the function, regardless whether it is inline or not.

If the intent of X_impl.h was to reduce the visual size of a header, then you should do it the other way around, include it at the end of X.h. inline must stay in that case.

like image 144
jrok Avatar answered Apr 01 '23 05:04

jrok