inlining overloaded functions

Hi,

I've been having some problems with multiple initializations of some overloaded functions. Here's is my class header file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#ifndef var_h
#define var_h 

class Var {
    private:          

      int states, var_number;
      
    public:      
         
      /// Default constructor      
      Var() : states(0), var_number(0){}
            
      /// constructor taking two ints as input.
      Var(int s, int n) : states(s), var_number(n){}	
	      
      int get_states() const {return states;}       
      int get_var_number() const {return var_number;}
      
};

bool operator<(const Var& v_1, const Var& v_2){return v_1.get_var_number() < v_2.get_var_number();}

bool operator==(const Var& v_1, const Var& v_2){return v_1.get_var_number() == v_2.get_var_number();}

bool operator!=(const Var& v_1, const Var& v_2){return v_1.get_var_number() != v_2.get_var_number();}

#endif  


Using this code I get multiple initialization errors of the overloaded functions 'operator<', 'operator==' and 'operator!='.

I realize that this is because I've written the bodies of these functions in the header file, and not in a separate cpp file. I found than an alternate solution is to make these function inline.

My question is which solution is better? To write these functions in a separate cpp file? Or to make them inline functions? Is there a problem with inlining overloaded functions?
Either solution will work, but each does different things. Inlining makes it so the compiler can replace a function call with the actual function body. Think of it like copy/pasting the function body into the actual code:

1
2
3
4
5
6
7
8
Var a, b;

if(a == b)  // if == operator is inlined.... this might get compiled to the same thing as this:

if(a.get_var_number() == b.get_var_number)  // and since get_var_number is also inlined
  //  that might get compiled to the same thing as this:

if(a.var_number == b.var_number)


If the functions are not inlined, the compiler will have your program "jump to" another area of code. This has some overhead, as some things need to get pushed to the stack, the program has to jump to (and back from) a separate area of the program, etc, etc.

The downside to inlining functions is that it might make your code larger (inlining large functions, for example can increase code size, which might result in slower code).

However since these functions are so small, I would definitely advise you inline them.
Excellent, thanks for the reply.

Never inlined a function before so it is good to know what is happening.

Topic archived. No new replies allowed.