Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct member functions definitions have differences if they are defined outside the struct body ?

A C++ question about struct member functions.

What is the difference between f1() and f2() except their names ?

 struct F{
   int f1(){
      return 0;  
    }
    int f2();    
 }; 
 int F::f2(){
     return 0;
 }

May I say f1() is inline but f2() is not ?

like image 507
user2420472 Avatar asked Nov 01 '25 01:11

user2420472


1 Answers

You are correct that f1 is inline and f2 is not, but its not just because it was defined inside the class. f2 could also be inline if it was defined as

inline int F::f2() {
    return 0;
}

The C++11 spec section 9.3 says that f1 is "defined in its class definition" and f2 is "defined outside of its class definition." It then states that any function defined inside its class definition is inline, while functions defined outside of its class definition must be explicitly marked as inline (like in my example above), or else they are non-inline (like your f2).

Inside the class definition vs. outside the definition is unimportant, other than making functions implicitly inline. The concept of inside a class definition and outside a class definition only appears in 9.3.2-9.3.5, while the broader concept of "inline" appears in other parts of the spec.

like image 136
Cort Ammon Avatar answered Nov 02 '25 14:11

Cort Ammon