When I use the pimpl idiom, is it a good idea to put all the methods definitions inside the class definition? For example:
// in A.h
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 putting a method definition inside a class definition is that (1) the implementation is visible in files that include the class definition, and (2) the compiler may make the method inline.
These are not problems in this case since the class is defined in a private file, and inlining has no effect since the methods are called in only one place.
The advantage of putting the definition inside the class is that you don't have to repeat the method signature.
So, is this OK? Are there any other issues to be aware of?
Defining the method outside the class To do this, we specify the name of the class, followed by the operator :: (scope resolution), then followed by the name of the method. In the code example below, we will create a class myclass and define a method mymethod outside the class.
A method is a procedure associated with a class and defines the behavior of the objects that are created from the class.
Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.
Methods are functions that belongs to the class. There are two ways to define functions that belongs to a class: Inside class definition. Outside class definition.
I think you answered your own question : both solutions are equivalent.
However, I wouldn't be so sure that 'inlining has no effect since the methods are called in only one place' : an additional call could exists when the functions are not inlined. But chances are that the compiler is smart enough to optimize them away from the one-line forwarding calls in the outer class.
In the end, I believe it's just a matter of taste.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With