Private C++ member function vs C function - c++

I have a C++ class, and in one of the member functions there is a duplicate section of code. So I've extracted this out into a function, however only this member function will call this new function. At the moment it's just a c function defined in the cpp file and not declared anyway else.
Is there any advantage to making this a private C++ member function, the code in the function itself doesn't use any instead variables of the class.

Well, if it's any addition to the argument, the newest CppCoreGuidelines say that you should "C.5: Place helper functions in the same namespace as the class they support". So they shouldn't be a part of the actual class, but part of the namespace that they reside in.

If you add it to the class then it becomes part of the classes signature.
As such making changes to the function signature would change the class signature. Given it would be a private function it is not likely that you would gain much by exposing it in that way.
If though it needs to access internals of the class then having as part of the class would likely simplify its implementation.
If it does not need to access the internals you can make add it to an anonymous namespace within the cpp file. That way the function symbol will not be exposed anywhere that is is not needed.

(Sort of an extended comment)
You've declared a free function in the .cpp file.
This a good design decision as other answers point out. The clearest thing you can have is a method only visible from that .cpp file that can't see or change state. I might be tempted to put it in the same namespace as the class as per the CppCoreGuidelines.
Equivilently, you could have declared a private static member function in your header file. This is static in the C#/Java sense rather than in either of the C senses (C++ has all of these meanings). However, I don't see the benifit as the only thing you gain is unnecessary recompilations.

Yes. Putting the function in class defines scope and context of it. This makes maintenance easier and also will allow you to extend its functionality in the future without significant code rewriting. Actually, in such cases I usually prefer making the function static in the class, i.e., meeting somewhere in the middle.

Related

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.

Class with no data members in C++

This may not be a question specific to C++ and more to do with Object oriented programming. I am new to this and I am doubtful of my design. I have a class Parser that basically implements many functions dealing parsing expressions, conversion from infix to postfix etc. I use these Parser functions in the main function. I realized that I do not need any data members for this class. Hence, I do not really need an object of this class. Hence, I ended up making every function static in the class. Is there something strange about this design. Should I have this as an interface instead? Any suggestions?
You want a parser and you know what you want it to do for you - this is in effect, your "interface".
Your current implementation of the parser doesn't need any member variables - therefore, to implement your interface, you don't need a class. So yes, do away with your static methods. Like Kevin says, using a namespace with plain old functions (non-static) is a great idea.
If you feel you will need to add a new parser that WILL need to maintain internal state, then you probably want to define an interface in (1) - a plain old publicly visible header file with function declarations inside a namespace of your choice is enough.
A class with nothing but static functions seems pretty indistinguishable from a namespace to me. So, why not just use a namespace?
The way to decide for this question is on how will the functions be used?
1) If all the functions are used in one file and do not need to be exported anywhere, then definitely use static functions. Why? Because you can just type them directly into the body of the class in the .cpp file and you do not have to worry about maintaining declarations and keeping parameters aligned. Because when a C++ class is parsed all the code inside each function defined inside the class body is skipped and then parsed once all the classes members have been declared, so the functions can all see each other and are in a better name situation.The compiler will also inline a lot of the smaller functions if you declare them directly in the class like that.
2) If the functions need to be used from outside the current .cpp file, then use normal functions. Because later they can be used from anywhere else and exporting them by name is easier.
It is common to make utility functions static, so, if the functions of your Parser class do not rely on each other, you totally can made them static. If they rely on each other, and it may be possible that the same functions can be done another way, you should consider to use an interface

Preferring non-member non-friend functions to member functions

This question title is taken from the title of item #23 in Effective C++ 3rd Edition by Scott Meyers. He uses the following code:
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
//This is the function in question.
void clearEverything();
};
//Alternative non-member implementation of clearEverything() member function.
void clearBrowser(WebBrowser& wb) {
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
};
While stating that the alternative non-member non-friend function below is better for encapsulation than the member function clearEverything(). I guess part of the idea is that there are less ways to access the internal member data for the WebBrowser if there are less member functions providing access.
If you were to accept this and make functions of this kind external, non-friend functions, where would you put them? The functions are still fairly tightly coupled to the class, but they will no longer be part of the class. Is it good practice to put them in the class's same CPP file, in another file in the library, or what?
I come from a C# background primarily, and I've never shed that yearning for everything to be part of a class, so this bewilders me a little (silly though that may sound).
Usually, you would put them in the associated namespace. This serves (somewhat) the same function as extension methods in C#.
The thing is that in C#, if you want to make some static functions, they have to be in a class, which is ridiculous because there's no OO going on at all- e.g., the Math class. In C++ you can just use the right tool for this job- a namespace.
So clearEverything is a convenience method that isn't strictly necessary. But It's up to you to decide if it's appropriate.
The philosophy here is that class definitions should be kept as minimal as possible and only provide one way to accomplish something. That reduces the complexity of your unit testing, the difficulty involved in swapping out the whole class for an alternate implementation, and the number of functions that could need to be overridden by sub-classes.
In general, you shouldn't have public member functions that only invoke a sequence of other public member functions. If you do, it could mean either: 1) you're public interface is too detailed/fine-grained or otherwise inappropriate and the functions being called should be made private, or 2) that function should really be external to class.
Car analogy: The horn is often used in conjunction w/ slamming on your brakes, but it would be silly to add a new pedal/button for that purpose of doing both at once. Combining Car.brake() and Car.honk() is a function performed by Driver. However, if a Car.leftHeadLampOn() and Car.rightHeadLampOn() were two separate public methods, it could be an example of excessively fine grained control and the designer should rethink giving Driver a single Car.lightsOn() switch.
In the browser example, I tend to agree with Scott Meyers that it should not be a member function. However, it could also be inappropriate to put it in the browser namespace. Perhaps it's better to make it a member of the thing controlling Web browser, e.g. part of a GUI event handler. MVC experts feel free to take over from here.
I do this a lot. I've always put them into the same .cpp as the other class member functions. I don't think there is any binary size overhead depending where you put them though. (unless you put it in a header :P)
If you want to go down this route the imlementation of clearEverything should be put in both the header (declaration) and implementation of the class - as they are tightly coupled and seems the best place to put them.
However I would be inclined to place them as a part of the class - as in the future you may have other things to clear or there may be a better or faster implementation to implement clearEverythingsuch as droppping a database an just recreate the tables

Private class functions vs Functions in unnamed namespace

I've found myself that I tend not to have private class functions. If possible, all candidates to private class function rather I put in to unnamed namespace and pass all necessary information as function parameters. I don't have a sound explanation why I'm doing that but at least it looks more naturally to me. As a consequence I need to expose less internal details in the header file.
What is your opinion - is it correct practice?
In the semi large projects where I usually work (more than 2 million lines of code) I would ban private class functions if I could. The reason being that a private class function is private but yet it's visible in the header file. This means if I change the signature (or the comment) in anyway I'm rewarded sometimes with a full recompile which costs several minutes (or hours depending on the project).
Just say no to that and hide what's private in the cpp file.
If I would start fresh on a large c++ project I would enforce PIMPL Idiom: http://c2.com/cgi/wiki?PimplIdiom to move even more private details into the cpp file.
I've done this in the past, and it has always ended badly. You cannot pass class objects to the functions, as they need to access the private members, presumably by reference (or you end up with convoluted parameter lists) so you cannot call public class methods. And you can't call virtual functions, for the same reason. I strongly believe (based on experience) that this is A Bad Idea.
Bottom line: This sounds like the kind of idea that might work where the implementation "module" has some special access to the class, but this is not the case in C++.
It basically comes down to a question of whether the function in question really makes sense as part of the class. If your only intent is to keep details of the class out of the header, I'd consider using the pimpl idiom instead.
I think this is a good practice. It often has the benefit of hiding auxiallary structures and data types as well, which reduces the frequency and size of rebuilds. It also makes the functions easier to split out into another module if it turns out that they're useful elsewhere.

Which is best for a repeating piece of code?

I have a class with two member functions that share a piece of code:
void A::First()
{
firstFunctionEpilogue();
sharedPart();
}
void A::Second()
{
secondFunctionEpilogue();
sharedPart();
}
Currently firstFunctionEpilogue(), secondFunctionEpilogue() and sharedPart() are not function calls but just pieces of code, sharedPart() code being duplicated. I want to get rid of the duplication.
The shared piece of code doesn't need access to any members of the class. So I can implement it as any of the three:
a static member function,
a const non-static member function or
a local function.
Which variant is better and why?
If your function accesses state but does not change it then use a const member function.
Your case:
If it your function 1) doesn't need access to any member of the code, and 2) is related to that class, then make it a static function of your class.
That way it is clear that it is not modifying state, nor based on the state of the object.
An extra case you didn't mention:
There is another thing you can do too. And that is to make your SharedPart take in a member function pointer and to call it and then process it's main body. If you have a lot of First(), Second(), Third(), Fourth(), ... such functions then this can lead to less code duplication. That way you don't need to keep calling SharedPart(); at the end of each member function, and you can re-use First(), Second(), THird(), ... without calling the SharedPart() of the code.
I'd say:
It probably doesn't matter, so it's not so much "best practice" as "just don't do anything crazy".
If the class and all its members are defined in its header, then a private static member function is probably best, since it clearly indicates "not for clients". But there are ways to do this for a non-member function: don't document it, put in a comment "not for clients", and stick the whole thing in namespace beware_of_the_leopard.
If the class member functions are defined in a .cpp file, then little helper functions like this are best as free functions in the .cpp file. Either static, or in an anonymous namespace.
Or it could be in a different class.
Or, if it's a member, it could be virtual.
There are a lot of decisions, and I wouldn't stress out about it too much. Generally, I opt for a const non-static member function as a default unless I have a good reason not to do it that way.
Prefer static if clients need to call it without having an instance
Prefer local functions if you don't want to clutter the .h file or you want it completely hidden in the .c
Make it a non-member function
The shared piece of code doesn't need access to any members of the class.
As a general rule, if a piece of code doesn't need access to any members of the class don't make it a member function! Try to encapsulate your classes as much as possible.
I'd suggest doing a non-member function in a separate namespace that would call the public methods and then call the function you made for the shared code.
Here is an example of what I mean :
namepsace Astuff{
class A{...};
void sharedPart(){...};
void first(const A& a);
void second(const A& a);
}
void Astuff::first(const A& a){
a.first();
sharedPart();
}
a static member function, a const
non-static member function or a local
function.
Generally, it should be a member function of another class, or at least non-static member of the class itself.
If this function is only called from instance members of a class - probably its logical meaning requires an instance, even if syntax does not. Can anything except this object provide meaningful parameters or make use of the result?
Unless it makes sense to call this function from outside of the object instance, it shouldn't be static. Unless it makes sense to call this function without accessing your class at all, it shouldn't be local.
Borrowing examples from Brian's comment:
if this function changes global state, it should be member of a class of global state;
if this function writes to file, it should be member of a class of file format;
if it's refreshing screen, it should be member of... etc
Even if it's a plain arithmetic expression, it may be useful to make it a member (static or not) of some ArithmeticsForSpecificPurpose class.
Make it a non-member non-friend function. Scott Meyer's has a great explanation for this here (and also Item 23 of Effective C++ 3rd Edition).
As a rule of thumb "try to keep it as local as possible but as visible as necessary".
If all code calling the function resides in the same implementation file, this means keeping it local to the implementation file.
If you'd make it a private static method of your class, it would not be callable by implementaions including your class, but it would still be visible to them. So every time you change the semantics of that method, all implementaions including your calls will have to recompile - which is quite a burden, since from their point of view, they don't even need to know those sementics.
Thus, in order to minimize unnecessary dependencies, you would want to make it a static global function.
However, if you should ever find yourself repeating this global function in mulitple implementation files, it would be time to move the function into a seperate header/implementaion file pair, so that all callers can include it.
Whether you place that function into a namespace, at global scope, or as a static function in a class is really up to taste.
On a final note, if you go for the global static function, there's a "more c++ like" version: anonymous namespaces. It has the nice property that it can actually store state and also prevents users for being able to even forward declare any of its functions.
// in your .cpp file
namespace /*anonymous*/
{
void foo()
{
// your code here
}
};
void MyClass::FooUser1() { foo(); }
void MyClass::FooUser2() { foo(); }