Should accessors be Inlined? - c++

This is the declaration in the header file:
class PrimeSieve
{
populate(int lim);
vector<int> sieve;
long long limit;
public:
unsigned int limit();
};
Should I define the accessor method in the .cpp file or in the .h, inline?
I'm new to C++, but I'd like to follow best practices. I've seen this around in some of the books—is this considered standard?
unsigned int limit() { return limit; };

Definitely write the accessor inline in the header file. It makes better optimizations possible, and doesn't reduce encapsulation (since changes to the format of private data require recompiling all units that include the header anyway).
In the case of a complicated algorithm, you might want to hide the definition in an implementation file. Or when the implementation requires some types/header files not otherwise required by the class definition. Neither of those cases applies to simple accessors.
For one-liners, put it inside the class definition. Slightly longer member functions should still be in the header file, but might be declared explicitly inline, following the class definition.

Most newer compilers are smart enough to inline what is necessary and leave everything else alone. So let the compiler do what its good at and don't try to second guess it.
Put all your code in the .cpp and the code declarations in the .h.

A good rule of thumb is to put all your code in the .cpp file, so this would argue against an inline function in the .h file.

For simple data types in classes fully visible to clients of the class, there is no real difference as you need to recompile the client whenever the class definition changes.
The main reason to make an accessor rather than use the member directly is to allow the implementation to remove the data member later on and still keep the interface compatible; if the interface containing the accessor is unchanged, the result is typically binary compatible, otherwise, it's source compatible. Having the accessor inline means defining it as part of the interface that you are changing, so you can ever only be source compatible.
The other reason to have an accessor is a DLL boundary: If your accessor needs to call into another function, and you allow it to be inlined, then this function's symbol needs to be exported to the client as well.
Depending on the complexity of the project, it can be beneficial to define an interface for your code as an abstract class, which allows you to change the implementation to your heart's content without the client ever seeing the change; in this case, accessors are defined as abstract in the interface class and clients cannot inline them, ever.

The argument for declaring the accessor inline is that this eliminates the call over-head, and can enable some further optimisations.
My experienced of measured performance is that the gain from doing this is usually rather modest. I consequently no longer do it by default.

More than being kind of global programming standards, these vary from organizations to organizaions. Of course, getLimit() would still be better than mere limit().

Related

Definition of function which is the class member

I have two functions, which are private members of class "Data":
class Date
{
private:
bool leapYear(int y);
void fillDate(int d, Month m, int y);
};
So, where is the best to define this functions:
in class definition;
in header file outside the class;
or in ".cpp" file?
You have the choice here. Here are some ideas to make your mind:
Inlining for speed is no longer a concern, since compilers are now good at link time optimization. So performance should not be a decision factor here (compilation speed matters too, but this is another bag of worms).
Small inline member functions, defined inside the class, may be an easy way to "document" what the class does. Also, this tends to keep the implementation localized, which is comfortable when reading the code. Don't overdo it however.
Large functions should in principle go into their own file, or at least outside the class definition, since they clutter the class definition code for no good reason. Template code is no exception.
Pimpl have advantages/disadvantages too, but here I don't see any good reason to introduce such beasts in your simple case. They are used typically to reduce dependencies between header files.
Here, if the implementation is small, you can write the code inline, inside the class. But you should put them in their own implementation (".cpp") file, if the logic is complex.
You can also start inline, and when the code has settled to something more complex, move the implementation to its own file.
I strongly discourage you to consider option 2. This gets you "Multiple definition" error by the linker if you include this file in more than one implementation file, because the definition will be copied (by the preprocessor) to each .cpp file.
My personal philosophy about this is to put all function definitions into the implementation (.cpp) file, because, first of all, it separates declarations (+ documentation) from definitions which adds to code clarity IMO, and, secondly, having all definitions in one place (the implementation file) makes it easier for me to find functions. In my experience it was always quite a nuisance to have to switch between header and implementation files to see whether this particular function I'm looking for was inlined / defined in the header or if it was in the implementation file. Having all function definitions in the implementation file means I know I will find the definition of any function in that file, and won't have to waste time switching and looking around.

C++ Declaration of class variables in header or .cpp?

So far, I've been using classes the following way:
GameEngine.h declares the class as follows
class GameEngine {
public:
// Declaration of constructor and public methods
private:
InputManager inputManager;
int a, b, c;
// Declaration of private methods
};
My GameEngine.cpp files then just implement the methods
#include "____.h"
GameEngine::GameEngine() {
}
void GameEngine::run() {
// stuff
}
However, I've recently read that variable declarations are not supposed to be in the header file. In the above example, that would be an inputManager and a, b, c.
Now, I've been searching for where to put the variable declarations, the closest answer I found was this: Variable declaration in a header file
However, I'm not sure if the use of extern would make sense here; I just declare private variables that will only be used in an instance of the class itself. Are my variable declarations in the header files fine? Or should I put them elsewhere? If I should put them in the cpp file, do they go directly under the #include?
Don't confuse a type's members with variables. A class/struct definition is merely describing what constitutes a type, without actually declaring the existence of any variables, anything to be constructed on memory, anything addressable.
In the traditional sense, modern class design practices recommend you pretend they are "black boxes": stuff goes in, they can perform certain tasks, maybe output some other info. We do this with class methods all the time, briefly describing their signature on the .h/.hpp/.hxx file and hiding the implementation details in the .cpp/.cc/.cxx file.
While the same philosophy can be applied to members, the current state of C++, how translation units are compiled individually make this way harder to implement. There's certainly nothing "out of the box" that helps you here. The basic, fundamental problem is that for almost anything to use your class, it kind of needs to know the size in bytes, and this is something constrained by the member fields and the order of declaration. Even if they're private and nothing outside the scope of the type should be able to manipulate them, they still need to briefly know what they are.
If you actually want to hide this information to outsiders, certain idioms such as PImpl and inlined PImpl can help. But I'd recommend you don't go this way unless you're actually:
Writing a library with a semi-stable ABI, even if you make tons of changes.
Need to hide non-portable, platform-specific code.
Need to reduce pre-processor times due to an abundance of includes.
Need to reduce compile times directly impacted by this exposure of information.
What the guideline is actually talking about is to never declare global variables in headers. Any translation unit that takes advantage of your header, even if indirectly, will end up declaring its own global variable as per header instructions. Everything will compile just fine when examined individually, but the linker will complain that you have more than one definition for the same thing (which is a big no-no in C++)
If you need to reserve memory / construct something and bind it to a variable's name, always try to make that happen in the source file(s).
Class member variables must be declared in the class definition, which is usually in a header file. This should be done without any extern keywords, completely normally, like you have been doing so far.
Only variables that are not class members and that need to be declared in a header file should be declared extern.
As a general rule:
Variables that are to be used with many functions in the same class go in the class declaration.
Temporary variables for individual functions go in the functions themselves.
It seems that InputManager inputManager; belongs in the class header.
int a, b, c; is harder to know from here. What are they used for? They look like temporary variables that would be better off in the function(s) they're used in, but I can't say for sure without proper context.
extern has no use here.

Where should I implement my class method?

I aware of three different kind of implementation "locations" for my class methods:
1) Define the method inside my class (.h file) and implement it in my .cpp file
//.h
class Foo
{
int getVal() const;
};
//.cpp
int Foo::getVal() const
{ return 0; }
2) Define and implement the method inside my class (.h file).
//.h
class Foo
{
int getVal() const
{ return 0; }
};
3) Define the method inside my class and implement it outside the class but inside my header file.
//.h
class Foo
{
int getVal() const;
};
int Foo::getVal() const
{ return 0; }
What are the main differences between these three approaches?
There are three elements to this question: readability (how good the code looks), compilation (how much the compiler can optimize it) and implementation hiding (If you use the code as a library, you may not want to explicitly share your special sauce with the world).
Method one exposes only the interface for the function in the header file. This means you show a nice clean interface, and your implementation is not exposed in plaintext. However, the code cannot be inlined across compilation units, so it has the potential to be a little slower in runtime (in practice, this only matters for a very, very very small percentage of the code). THIS SHOULD BE YOUR DEFAULT WAY TO GO.
Method 2 is implicit inlining. Long functions will clutter up your class which (imho) is bad. Also exposes your implementation to the world. However, the function can be inlined and is less verbose than defining it in another place. I reserve this for very small functions.
Method 3 is actually illegal, as you will break the one-definition rule, but the following is fine:
//Foo.h
class Foo {
int getVal() const;
};
inline int Foo::getVal() const {
return 0;
}
I use this when I want to keep the class definition clean but want the function definition in the header file (for inlinable or template functions).
(1) will compile faster for a large project (only have to compile the definition of getVal once in Foo.cpp, and only have to recompile one thing if definition changes), and you get a very clear interface for a class for people who want to look it up. On the other hand, you can't inline getVal().
(2) and (3) will compile slower and add way more dependencies to your definitions changing. But you can inline getVal(). Also this is required if getVal is a template function. NOTE (3) will cause linker errors if your header is included multiple times - you'll have to mark remember to label your function inline. This is a good reason to prefer (1) and (2) to (3).
Really it's not a matter of picking (1) vs (2). You will probably use both in large projects - put the definitions of the functions that should be inlined (and templates) in the header, and put the ones that inlining makes less sense for in the cpp.
A minor note before I begin, there are lots of words that are very similar used to describe these things, I will be using declaration for the portion in the header file (int getVal() const) and implementation for the portion in the cpp file (int Foo::getVal() const). Apologies if these aren't perfectly accurate.
Also note that benefits are penalties for the others, in case that isn't clear.
1) Define the method inside my class (.h file) and implement it in my .cpp file
This is considered the standard method, and generally accepted to be the default (there are numerous exceptions, so default might be a little strong).
It separates the declaration from the implementation. This provides a few benefits:
You only need to compile the implementation once. This could potentially save compilation time.
You only need the declaration to reference. This can avoid ordering issues and is vital for circular references between classes.
You don't distribute your implementation, this can be good for closed source systems as you often have to distrbute lots of your .h files for others to plug into your system.
2) Define and implement the method inside my class (.h file).
This is called an inline implementation, it should be used in simple implementations only. It has a few benefits too:
Most compilers take this as a huge inline hint. It doesn't guarantee inling but it is very likely, which for simple methods can be a win. Property style methods are a common example.
Your implementation is trivial to find as it is straight in the declaration.
3) Define the method inside my class and implement it outside the class but inside my header file.
I haven't seen this before, but would assume it is used when the definition is non-trivial but you want the inline benefits of 2. IdeaHat mentions that the inline keyword is required in this case.

To inline or not to inline

I've been writing a few classes lately; and I was wondering whether it's bad practice, bad for performance, breaks encapsulation or whether there's anything else inherently bad with actually defining some of the smaller member functions inside a header (I did try Google!). Here's an example I have of a header I've written with a lot of this:
class Scheduler {
public:
typedef std::list<BSubsystem*> SubsystemList;
// Make sure the pointer to entityManager is zero on init
// so that we can check if one has been attached in Tick()
Scheduler() : entityManager(0) { }
// Attaches a manager to the scheduler - used by Tick()
void AttachEntityManager( EntityManager &em )
{ entityManager = &em; }
// Detaches the entityManager from a scheduler.
void DetachEntityManager()
{ entityManager = 0; }
// Adds a subsystem to the scheduler; executed on Tick()
void AddSubsystem( BSubsystem* s )
{ subsystemList.push_back(s); }
// Removes the subsystem of a type given
void RemoveSubsystem( const SubsystemTypeID& );
// Executes all subsystems
void Tick();
// Destroys subsystems that are in subsystemList
virtual ~Scheduler();
private:
// Holds a list of all subsystems
SubsystemList subsystemList;
// Holds the entity manager (if attached)
EntityManager *entityManager;
};
So, is there anything that's really wrong with inlining functions like this, or is it acceptable?
(Also, I'm not sure if this'd be more suited towards the 'code review' site)
Inlining increases coupling, and increases "noise" in the class
definition, making the class harder to read and understand. As a
general rule, inlining should be considered as an optimization measure,
and only used when the profiler says it's necessary.
There are a few exceptions: I'll always inline the virtual destructor of
an abstract base class if all of the other functions are pure virtual;
it seems silly to have a separate source file just for an empty
destructor, and if all of the other functions are pure virtual, and
there are no data members, the destructor isn't going to change without
something else changing. And I'll occasionally provide inlined
constructors for "structures"—classes in which all data members
are public, and there are no other functions. I'm also less rigorous
about avoiding inline in classes which are defined in a source file,
rather than a header—the coupling issues obviously don't apply in
that case.
All of your member functions are one-liners, so in my opinion thats acceptable. Note that inline functions may actually decrease code size (!!) because optimizing compilers increase the size of (non-inline) functions in order to make them fit into blocks.
In order to make your code more readable I would suggest to use inline definitions as follows:
class Scheduler
{
...
void Scheduler::DetachEntityManager();
...
};
inline void Scheduler::DetachEntityManager()
{
entityManager = 0;
}
In my opinion thats more readable.
I think inlining (if I understood you right, you mean the habit of writing trivial code right into the header file, and not the compiler behaviour) aids readability by two factors:
It distinguishes trivial methods from non-trivial ones.
It makes the effect of trivial methods available at a glance, being self-documenting code.
From a design POV, it doesn't really matter. You are not going to change your inlined method without changing the subsystemList member, and a recompile is necessary in both cases. Inlining does not affect encapsulation, since the method is still a method with a public interface.
So, if the method is a dumb one-liner without a need for lengthy documentation or a conceivable need of change that does not encompass an interface change, I'd advise to go for inlining.
It will increase executable size and in some occasions this will lead to worse performance.
Keep in mind that an inline method requires it's source code to be visible to whoever uses it (ie. code in the header) this means that a small change in the implementation of your inlined methods will cause a recompilation on everything that uses the header where the inline method was defined.
On the other hand, it is a small performance increase, it's good for short methods that are called really frequently, since it will save you the typical overhead of calling to methods.
Inline methods are fine if you know where to use them and don't spam them.
Edit:
Regarding style and encapsulation, using inline methods prevents you from using things like Pointer to implementation, forward declarations, etc.. since your code is in the header.
Inlining has three "drawbacks" at least:
inline functions are at odds with the virtual keyword (I mean conceptually, IMO, either you want a piece of code to be substituted for the function call, or you want the function call to be virtual, i.e. polymorphic; anyway, see also this for more details as to when it could make sense practically);
your binary code will be larger;
if you include the inline method in the class definition, you reveal implementation detail.
Apart from that it is plainly ok to inline methods, although it is also true that modern compilers are already sufficiently smart to inline methods on their own when it makes sense for performance. So, in a sense I think it is better to leave it to the compiler altogether...
Methods inside class body are usually inline automatically. Also, inline is a suggestion and not a command. Compilers are generally smart enough to judge whether to inline a function or not.
You can refer to this similar question.
In fact you can write all your functions in the header file, if the function is too large the compiler will automatically not inline the function. Just write the function body where you think it fits best, let the compiler decide. The inline keyword is ignored often as well, if you really insist on inlining the function use __forceinline or something similar (I think that is MS specific).

Member function definition

What is the right approach to take:
Define the member (class) function inside the class?
Define the member (class) function outside the class?
Thanks.
Assuming you're talking about these three possibilities:
Method defined in class definition in header file.
Method define outside class definition in header file.
Method define outside class definition in implementation file.
Then project and company guidelines may force you to use (1) or (3) always.
When you have a choice, it's IMHO best to adapt to circumstances at hand, considering things such as
Do you want a header-only module? Then (1) as default, (2) possible.
Is the method a large beast? Then (2) or (3).
Template method specialization? Then (2) or (3).
There is a build-time problem (slow builds)? Indicates (3).
Template class? (1) or possibly (2)
But except where the choice is effectively forced on you, above all consider the clarity of your code.
Cheers & hth.,
A common advice is to keep headers as simple and clean as possible. Headers will be included by external code, and they will have to process everything that you have written there. If you write a method in the header, all translation units will compile that function, only so that the linker can discard all but one of them later on.
If your code has an internal dependency on a type or library that is not part of your interface, then by inlining the code of the member function in the class declaration the definition of that class or the headers of that library will have to be included in your header, and that means that you are leaking your implementation details to your users.
Unless the member function definition is trivial (in an informal sense) and doesn't introduce any additional dependencies I would normally define a member function outside of the class body in a separate source file.
It's often a matter of style but there are some cases in which it is necessary and many other cases in which it is desirable to define function outside of the class body.
For example, in the cases where you have interdependent classes and only a forward declaration of another class can be made available before the class definition, a member function which uses the definition of that other class can only be defined outside of the class body after a full definition of the other class has been provided.
Do you mean "in the class declaration / .h file" vs "in a .cpp file using ::" ?
If so I always go for the latter. When it comes to debugging, it's a lot easier to step through and see what's going on. It also helps declutter the class declaration, which doesn't need to know any implementation details"
If you want to define a function within a class the most basic syntax looks generally like:
class Object
{
int property;
void doSomething()
{
property=100;
}
};
If you want to define a function outside it is similar to declaring functions before main and in library files. In your class you have:
class Object
{
int property;
void doSomething();
};
Then somewhere after your class, after the main() function or in an included file you can have the definition:
void Object::doSomething()
{
property=100;
}
Some place classes in a header file and the definitions in a cpp file used by that header. Various techniques possible.
Both of these approaches are valid. Often I will include very small and/or core class functionality directly within the class and other functions which do heavier bulk work I tend to separate. Try to think the difference in coming upon your code and wanting to alter it.
if we see according to performance issue than it is more effective way to declare the function in the class . becouse at the compile time it conects all the funcation calls and other components so it will easy and must be faster to get all in one source...