Including all methods in a class definition

When I use the pimpl idiom, is it useful to put all the method definitions inside the class definition? For example:

// in Ah class A { class impl; boost::scoped_ptr<impl> pimpl; public: A(); int foo(); } // in A.cpp class A::impl { // method defined in class int foo() { return 42; } // as opposed to only declaring the method, and defining elsewhere: float bar(); }; A::A() : pimpl(new impl) { } int A::foo() { return pimpl->foo(); } 

As far as I know, the only problems with setting the method definition inside the class definition is that (1) the implementation is visible in files that include the class definition, and (2) the compiler can make the inline method.

This is not a problem in this case, since the class is defined in a private file, and the attachment is not affected, since the methods are called only in one place.

The advantage of placing a definition inside a class is that you do not need to repeat the method signature.

So, is that normal? Are there any other issues you need to know about?

+6
c ++ inline pimpl-idiom
source share
4 answers

I think you answered your question: both solutions are equivalent.

However, I would not be so sure that "inlining has no effect, since methods are called only in one place": an additional call may exist when functions are not built-in. But there is a chance that the compiler is smart enough to optimize them from single-line call forwarding calls in an external class.

In the end, I think it's just a matter of taste.

+3
source share

Benefits:

  • all class code is localized

Disadvantages:

  • for large classes: when scrolling is required, it becomes more difficult to find out which class the function belongs to.
  • Dependencies are easier to decide when functions are after all class declarations. Otherwise, some class declarations may need to be moved after others, and some functions still need to be moved after the class declaration, when there is interdependence between the inner classes.
+2
source share

I usually don’t add methods to the inner class of Impl, but I don’t see any problem if you define inline methods. It seems to me much more readable than a separate declaration and definition.

+1
source share

Regardless of whether the compiler depends on the methods associated with the compiler and the parameters passed.

In the case of the pimpl idiom, I don’t think it matters if the methods are defined in the body of Imp or not. I personally like that they are defined externally because it is easy to see what is really important (like member variables and a list of methods).

0
source share

All Articles