Solved

inline function

Posted on 1998-04-11
20
470 Views
Last Modified: 2010-04-10
I would like to ask if I want to declare and define an inline function in a class(with a .h and
a .cpp), then which of the following is correct?

(a) class X{
          inline void func();
          int a;
      };
     void X::func(){a=1};

(b) class X{
          void func();
          int a;
      };
     inline void X:: func(){a=1};

(c) class X{
          inline void func();
          int a;
      };
     inline void X:: func(){a=1};

(d) class X{
          inline void func(){a=1};
          int a;
      };

(e) class X{
          void func(){a=1};
          int a;
      };

I know (d) or (e) may be correct but how about if I don't want to expose my code in the
.h file, what should I do?

Thank you in advance.
0
Comment
Question by:syyung6
  • 10
  • 9
20 Comments
 
LVL 22

Accepted Solution

by:
nietod earned 100 total points
ID: 1184196
answer coming.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184197
A is syntacticaly fine and may inline the function.
B is syntactically fine but probably won't result in an inline function.
A is syntacticaly fine and may inline the function.
D is syntacticaly fine and will probably (best chance) inline the function.
E is syntacticaly fine and will probably inline the function.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184198
All the methods you propose will compile, but some have a better chance of actually inlining the function.  D and E are the most likely to result in an inline function.  B is likely to NOT result in an inline function.  The compiler's features, the nature of the function, and the nature of how the function is used will also have an effect on whethor or not a function is inlined.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184199
As to D and E exposing the code.  That is why there is a good chance that they will inline.  Many compilers will need to see the code to be inlined at compile time or they won't inline.  Some of these compilers will need to see it in the header file, if its not there you don't get the function inline.  There are ways around this, but there's not garantee the compiler/linker will employee them.  So if you really want a function inlined, D or E are best.
0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184200
nietod - I'll have to try that .. blocking a question while you type it in to ensure noone else gets a chance to answer.

0
 
LVL 22

Expert Comment

by:nietod
ID: 1184201
I have to warn you--A few people have accused me of being dishonest by using it.  However, I really think it is the most fair way to handle things.  It prevents two experts from working long an hard on the same answer and it allows an expert to take the time to write a complete answer rather than rushing in order to beat other experts.
0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184202
The syntax used will make no difference as to the likelyhood of inlining.

As long as the code is correctly inlined (either with the inline keyword, or because it is actually written with the body of the code in-line) it will be subject to inlining.

However, you cannot FORCE a function to be inlined - you can only suggest to the compiler that it be implemented that way.  A compiler may choose to inline all potentially in-linable functions (not just the ones you tell it), or it may inline none, or basically do whatever it wants to do.

It is NOT possible to hide a global or class in-line implmentation in a .cpp, because if the compiler cannot see it when it includes the .h, then it cannot inline it.

0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184203
I've been gazumped while typing in an answer before - I agree that it is VERY annoying.  As I said - I'll try this technique myself to avoid this annoyance .. but I think a brief summary of what the answer entails is more "ethical" that a single line "answer coming" - that seems just a little bit like cheating.

In this case a simple answer like "all syntactically fine, but some may not inline .. details follow" would seem more ethically acceptable.

0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184204
The answer supplied BTW is not really corect, in that it implies that some of the methods will not inline correctly and that, for some reason, some are better than others.

There are two ways of declaring an inline (class member) function.

1) put the implementation within the class declaration.
eg.
class X{
          void func(){a=1};
          int a;
      };
the inline keyword can optionally be used here if you want: ie:

class X{
          inline void func(){a=1};
          int a;
      };

2) put the implementation outside the class declaration and use the inline keyword on either the declaraion and/or the body.

Both these methods have EXACTLY the same chance of generating actual inlined code.

The first has the advantage (for very small inline functions) of avoiding extra lines of code.

The second has the advantage that it allows more flexibility wrt use of header files (expecially if classes refer to each other recursively), and allows the implementation to be in a different include file from the class declaration.  You can even turn inlining on/off using macros with this technique.

myclass.h:
#ifdef USE_INLINING
#define INLINE inline
#else
#define INLINE
#endif
class X{
          INLINE void func();
          int a;
      };
#ifdef USE_INLINING
#include "myclass.inl"
#endif

myclass.inl:
INLINE void X::func() {
  return a;
};

myclass.cpp:
#ifndef USE_INLINING
#include "myclass.inl"
#endif

0
 
LVL 22

Expert Comment

by:nietod
ID: 1184205
You wrote

2) put the implementation outside the class declaration and use the inline keyword on either the
      declaraion and/or the body.

      Both these methods have EXACTLY the same chance of generating actual inlined code.

Not true!.  Most compilers will not inline under these circumstances.  They cannot because they don't have the associated code to inline.  Unless the compiler maintains a "project database" type of file it might have no clue where to even find the code.  It would have no clue what file contains the code and it might not even have the file at compile time.  Schemes that use linker to fill in the inline code are possible but make other things like many optimizations, harder.
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184206
Sorry, but it IS TRUE!

You appear to have misunderstood what I actually said.  I did NOT say to put the implementaion in a cpp file - I said to put it outside the _class declaration_

eg.

myfile.h:

class X {
public:
  inline X();
};
...
inline X::X() {
  // body of inline constructor here
}

this works _exactly_ the same as

class X {
public:
  X() {
    // body of inline constructor here
  }
};

Both methods have the same change of inlining as each other .. but removing the implementation from the class declaration allows more flexibility, and so in general is the better solution (except for very simple inline functions).

However, as we have both said, the implementation cannot be hidden in a .cpp file as it has to be available in each compilation unit where the class declaration is included.

But there are equally valid syntactic choices for inlining.

0
 
LVL 22

Expert Comment

by:nietod
ID: 1184207
Opps!.  You are right.  
0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184208
<modesty off> Of course :-) <modesty on>

Sometimes the separate form is necessary (eg. when two classes reference each other from inline definitions
eg.

class A;
class B;
class A {
public:
  void f() {
    B b;
    b.g();
  }
  void h();
};
class B {
  void g() {
    A a;
    a.h();
  }
};

won't compiler no matter which order you declare the classes, whereas

class A {
public:
  inline void f();
  void h();
};
class B {
  inline void g();
};

inline void A::f() {
  B b;
  b.g();
}
inline void B:g() {
  A a;
  a.h();
}

will work.

0
 

Author Comment

by:syyung6
ID: 1184209
Thank you very much for helping the C++ newbie!
Some more questions, do you mean that whether the code is inlined or not is up to the compiler, even we put the keyword "inline"? And for (e), will the compiler inlines it automatically? So, I wonder why C++ language have the reserved word "inline".
0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184210
inline is a hint only.  It says "I would like this function to generate in-line code if possible".  It is up to the compiler to determine when (if at all) it will do this.  Some functions cannot be inlined all the time (eg recursive functions, functions called thru function pointers, virtual functions).

As I pointed out, none of the examples A..E are more or less likely to result in inlining.

The inline reserved work is there so that one CAN declare a function inline (with no need for a .cpp), without the inline keyword only code like your example E would be possible .. the other examples would result in multiple function bodies (the function body would be compiled in every source file where the .h was included).

Maybe you should ask this as a separate question .. so I can get some points too :-)

Roger

0
 
LVL 22

Expert Comment

by:nietod
ID: 1184211
Note one subtle point in Ronslow's comments.  (So subtle I missed it the first time.)  If the procedure body is in the include (.h) file there is a good chance the function will be inlined (not garrunteed, though).  But if the procedure body is in a seperate source file (.cpp) there is a good chance it won't be inlined.  This

*****************HEADER FILE*************

class Cls
{
puiblic:
   inline int F():
}

int Cls::F()
{
}

This has a good chance of being inlined, but

*****************HEADER FILE*************

class Cls
{
puiblic:
   inline int F():
}
*****************SOURCE CODE FILE*************
int Cls::F()
{
}

This is not likely to be inlined.
0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184212
Again, no...

In the example you give above, function F() WILL be just as likely to be inlined (just as if F() was declared in the header file).

However, if the same header file is #included in another source file and that file uses F(), then that other source file will also need a definition for F()

Remember, when it comes to compiling each source file, #included header files become logically a part of the source and all get compiled as one lump, so it does not matter _where_ the implementations of inline functions appear, as long as they appear _somewhere_ in the combined compilation unit of include files and source file.

0
 
LVL 22

Expert Comment

by:nietod
ID: 1184213
Opps I was accusing you of being imprecise and was equally impricise.  What I meant was that if the function body is written in one source file.  It will probably not be inlined in OTHER source files.  It probably will be inlined in the one source file where it is included.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184214
What it comes down to is this.  If the compuler can "see" the function body when it compiles a source file, it has a good chance of making a function inline (there are still reasons why it might not be able to)  To "see" the function body, it has to be in the current source file or in an include file.  If the function body is in another source file, it probably won't inline it.

How's that Ronslow?
0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1184215
Spot on - couldn't have said it better myself :-)

We'll have to do this again someday, nietod !!

0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now