Is defining auxiliary functions outside of an object allowed? - c++

I have a class and a given quite complicated method for the sake of which I've defined some auxiliary functions, which aren't however used anywhere else. Now I'm wondering whether I should
add them to my class - it seems to be what it should be done according to the OOP paradigm
keep them outside, i.e. separately, only in my implementation file - since filling up my class definition with that sort of semi-redundant methods would make my class definition less readable.
My question is what should I do when C++ style is concerned. I feel that the second solution goes against the OOP principles, though C++ isn't an object-oriented language but a hybrid one. The functions I mention, if implemented as class methods, would be static.

Put them in an Unnamed namespace inside your source file.
The unnamed namespace allows your functions to be visible within the translation unit, but not outside the translation unit. Your functions still have an external linkage but they are simply invisible to anyone outside the translation unit.

FWIW, I'm going to add this: the answers given so far are fine, but since C++11 I found that for strictly auxiliary functions there is a better and less intrusive solution:
Define them as lambdas inside the method they serve.
This will make them invisible everywhere else and give them proper access permissions without requiring the use of a friend declaration or making them private static members.

Related

Is it legal to have 2 header files for the same class in c++?

In a project I read, there are two header files and two declarations for the same class. One is used by programs that use this library, serving as an interface. Another is used by the library itself.The interface header file is simpler. It doesn't contain private members and has less methods. Even methods that appear in both files may not appear in the same order. I wonder if it is legal to have 2 header files for the same class? If it is not, what are the possible consequences?
In short
This is not legal at all. Depending of what's in the private part that is committed, it might work on some implementations, but it might very well fail at the first change or new release of the compiler. Just don't. There are better ways to achieve the intended objectives.
Some more explanations
Why it's not legal?
It's the One Definition Rule (ODR). It's defined in the standard, in a long section [basic.def.odr]. In summary, it is possible to have multiple definition of the same class in different compilation units (e.g. your code, and the library's code), but only if it's exactly the same definition. This requires that it's exactly the same sequence of tokens that are used for the two definitions, which is clearly not the case if you leave out the private members. (Note that there are additional requirements as well, but the first one is already broken, so I short-circuit).
Why does it work in practice in some cases even if not legal?
It's purely implementation dependent luck. I will not develop this topic, in order not to encourage dangerous behavior.
What alternatives
Just use the same definition of the class everywhere. Private members are private, so what's the risk of leaving them where they were ?
Ok, sometimes the definition of private members would require to disclose also private types, end as a chain reaction, much too much. In this case, you may think of:
The simple opaque pointer technique, which uses a pointer to a private implementation class, whose type is declared but that is not defined in the compilation units that do not need to know.
The more elaborate bridge pattern, which allows to build class hierarchies for an abstraction, and class hierarchies with the implementation. It can be used in a similar way than the opaque pointer, but would allow for different kind of private implementation classes (it's a complex pattern, and it's an overkill if it's just for hiding private details).

Should I use static or inline?

I am writing a header-only library, and I can’t make up my mind between declaring the functions I provide to the user static or inline. Is there any reason why I should prefer one to the other in that case?
They both provide different functionalities.
There are two implications of using the inline keyword(§ 7.1.3/4):
It hints the compiler that substitution of function body at the point of call is preferable over the usual function call mechanism.
Even if the inline substitution is omitted, the other rules(especially w.r.t One Definition Rule) for inline are followed.
The static keyword on the function forces the inline function to have an internal linkage(inline functions have external linkage) Each instance of such a function is treated as a separate function(address of each function is different) and each instance of these functions have their own copies of static local variables & string literals(an inline function has only one copy of these)
Note: this answer is for C++. For C, see caf's answer. The two languages differ.
static has two relevant meanings:
For a function at namespace scope, static gives the function internal linkage, which in practical terms means that the name is not visible to the linker. static can also be used this way for data, but for data this usage was deprecated in C++03 (§D.2 in C++03 Annex D, normative). Still, constants have internal linkage by default (it's not a good idea to make that explicit, since the usage for data is deprecated).
For a function in a class, static removes the implicit this argument, so that the function can be called without an object of the class.
In a header one would usually not use internal linkage for functions, because one doesn't want a function to be duplicated in every compilation unit where the header is included.
A common convention is to instead use a nested namespace called detail, when one needs classes or functions that are not part of the public module interface, and wants to reduce the pollution the ordinary namespace (i.e., reduce the potential for name conflict). This convention is used by the Boost library. In the same way as with include guard symbols this convention signifies a lack of module support in current C++, where one is essentially reduced to simulating some crucial language features via conventions.
The word inline also has two relevant meanings:
For a function at namespace scope it tells the compiler that the definition of the function is intentionally provided in every compilation unit where it’s used. In practical terms this makes the linker ignore multiple definitions of the function, and makes it possible to define non-template functions in header files. There is no corresponding language feature for data, although templates can be used to simulate the inline effect for data.
It also, unfortunately, gives the compiler a strong hint that calls to the function should preferably be expanded “inline” in the machine code.
The first meaning is the only guaranteed meaning of inline.
In general, apply inline to every function definition in a header file. There is one exception, namely a function defined directly in a class definition. Such a function is automatically declared inline (i.e., you avoid linker protests without explicitly adding the word inline, so that one practical usage in this context is to apply inline to a function declaration within a class, to tell a reader that a definition of that function follows later in the header file).
So, while it appears that you are a bit confused about the meanings of static and inline – they're not interchangable! – you’re essentially right that static and inline are somehow connected. Moving a (free) function out of a class to namespace scope, you would change static → inline, and moving a function from namespace scope into a class, you would change inline → static. Although it isn’t a common thing to do, I have found it to be not uncommon while refactoring header-only code.
Summing up:
Use inline for every namespace scope function defined in a header. In particular, do use inline for a specialization of a function template, since function templates can only be fully specialized, and the full specialization is an ordinary function. Failure to apply inline to a function template specialization in a header file, will in general cause linking errors.
Use some special nested namespace e.g. called detail to avoid pollution with internal implementation detail names.
Use static for static class members.
Don't use static to make explicit that a constant has internal linkage, because this use of static is deprecated in C++03 (even though apparently the deprecation was removed in C++11).
Keep in mind that while inline can’t be applied to data, it is possible to achieve just about the same (in-practice) effect by using templates. But where you do need some big chunk of shared constant data, implemented in a header, I recommend producing a reference to the data via an inline function. It’s much easier to code up, and much easier to understand for a reader of the code. :-)
static and inline are orthogonal. In otherwords, you can have either or both or none. Each has its own separate uses which determine whether or not to use them.
If that function is not sharing the class state: static. To make a function static can benefit from being called at anywhere.
If the function is relatively small and clear: inline
(This answer is based on the C99 rules; your question is tagged with both C and C++, and the rules in C++ may well be different)
If you declare the function as just inline, then the definition of your function is an inline definition. The compiler is not required to use the inline definition for all calls to the function in the translation unit - it is allowed to assume that there is an external definition of the same function provided in another translation unit, and use that for some or all calls. In the case of a header-only library, there will not be such an external definition, so programs using it may fail at link time with a missing definition.
On the other hand, you may declare the function as both inline and static. In this case, the compiler must use the definition you have provided for all calls to the function in the translation unit, whether it actually inlines them or not. This is appropriate for a header-only library (although the compiler is likely to behave exactly the same for a function declared inline static as for one declared static only, in both cases inlining where it feels it would be beneficial, so in practice there is probably little to be gained over static only).

Multiple classes in one .cpp file

I was wondering if it is considered bad practice to have multiple classes in one .cpp file. I have a background in Objective-C, where this is rarely done.
It makes for less readable code because you usually expect a class's definition to be in the header with the same name and the implementation in an implementation file with the same name.
There are cases in practice where a class is relatively small and closely-related small classes can be grouped together, but it's on a case-by-case basis.
As the other answer points out, it makes for less readable code.
It is important to also consider the scope of a nested class:
A nested class is declared within the scope of another class. The name
of a nested class is local to its enclosing class. Unless you use
explicit pointers, references, or object names, declarations in a
nested class can only use visible constructs, including type names,
static members, and enumerators from the enclosing class and global
variables.
Source

When should I write the keyword 'static' before a non-member function?

I've recently seen a bit on SO about the static keyword before a function and I'm wondering how to use it properly.
1) When should I write the keyword static before a non-member function?
2) Is it dangerous to define a static non-member function in the header? Why (not)?
(Side Question)
3) Is it possible to define a class in the header file in a certain way, so that it would only be available in the translation unit where you use it first?
(The reason that I'm asking this is because I'm learning STL and it might be a good solution for my predicates etc (possibly functors), since I don't like to define functions other than member-functions in the cpp file)
(Also, I think it is related in a way to the original question because according to my current reasoning, it would do the same thing as static before a function does)
EDIT
Another question that came up while seeing some answers:
4) Many people tell me I have to declare the static function in the header, and define it in the source file. But the static function is unique to the translation unit. How can the linker know which translation unit it is unique to, since header files do not directly relate to a source file (only when you include them)?
static, as I think you're using it, is a means of symbol hiding. Functions declared static are not given global visibility (a Unix-like nm will show these as 't' rather than 'T'). These functions cannot be called from other translation units.
For C++, static in this sense has been replaced, more or less, by the anonymous namespace, e.g.,
static int x = 0;
is pretty equivalent to
namespace {
int x = 0;
}
Note that the anonymous namespace is unique for every compilation unit.
Unlike static, the anonymous namespace also works for classes. You can say something like
namespace {
class Foo{};
}
and reuse that class name for unrelated classes in other translation units. I think this goes to your point 3.
The compiler actually gives each of the symbols you define this way a unique name (I think it includes the compilation time). These symbols are never available to another translation unit and will never collide with a symbol from another translation unit.
Note that all non-member functions declared to be inline are also by default static. That's the most common (and implicit) use of static. As to point 2, defining a static but not inline function in a header is a pretty corner case: it's not dangerous per se but it's so rarely useful it might be confusing. Such a function might or might not be emitted in every translation unit. A compiler might generate warnings if you never actually call the function in some TUs. And if that static function has within it a static variable, you get a separate variable per translation unit even with one definition in a single .h which might be confusing. There just aren't many (non-inline) use cases.
As to point 4, I suspect those people are conflating the static member function meaning of static with that of the linkage meaning of static. Which is as good a reason as any for using the anonymous namespace for the latter.
The keyword "static" is overloaded to mean several different things:
It can control visibility (both C and C++)
It can persist a variable between subroutine invocations (both C and C++)
... and ...
It can make a method or member apply to an entire class (rather than just a class instance: C++ only)
Short answer: it's best not to use ANY language facility unless
a) you're pretty sure you need it
b) you're pretty sure you know what you're doing (i.e. you know WHY you need it)
There's absolutely nothing wrong with declaring static variables or standalone functions in a .cpp file. Declaring a static variable or standalone function in a header is probably unwise. And, if you actually need "static" for a class function or class member, then a header is arguably the BEST place to define it.
Here's a good link:
http://www.cprogramming.com/tutorial/statickeyword.html
'Hope that helps
You should define non-member functions as static when they are only to be visible inside the code file they were declared in.
This same question was asked on cplusplus.com

Class member function declaration doubt

I'm reading a C++ tutorial and I've ran into this sentence:
The only difference between defining a class member function
completely within its class or to include only the prototype and later
its definition, is that in the first case the function will
automatically be considered an inline member function by the compiler,
while in the second it will be a normal (not-inline) class member
function, which in fact supposes no difference in behavior.
I know what an inline function is, my doubt is about which style to choose. Should I define every function inside its class or outside? Perhaps the simplest functions inside and the other outside?
I fear that defining every function inside a class (i.e. having complex inline functions) might mess up the resulting code and introduce debugging problems or weird behaviors during execution. And, finally, there's the "coding style" issue. So,
which approach is better?
Thank you :)
My style: I sometimes will put extremely short (one or two liner) functions in the class itself. Anything longer that I still want as an inlined function go as inline qualified implementations after the class definition, and oftentimes in a separate file that the header #includes at the end of the class definition.
The rationale for putting an inlined function outside the class is that the implementation of some function usually just gets in the way of a human reader's overall understanding of the class. A twenty line function can usually be summarized in a one line comment -- and that comment is all that is needed when you are reading the class definition. If you need more, go to the function definition, or better yet, Read The Fine Documentation. (Expecting someone to Read The F*** Code is a poor substitute for Fine Documentation.)
The best solution is to separate interface and implementation. Interface is your h-file. Put only prototypes there. Implementation goes to cpp-file. This approach has the following advantages:
Compilation goes faster because there is no need to compile function bodies several times.
Header dependency is simpler because there is no need to include all headers to h-file. Some of the headers are needed only in cpp-file and you can use forward declarations in h-file. Also you can avoid circular dependencies.
The last but not the least - it is easier for human beings to understand interface of your class. There is no code mess.
To answer the part of "Which approach is better?" - From C++ FAQ -
There are no simple answers: You have to play with it to see what is best. Do not settle for simplistic answers like, "Never use inline functions" or "Always use inline functions" or "Use inline functions if and only if the function is less than N lines of code." These one-size-fits-all rules may be easy to write down, but they will produce sub-optimal results.
Neither approach is better per se its a matter of preference and style. Personally I always think that defining the functions explicitly in a seperate .inline file is the best way. This way you are very explicit over what you do and you keep the header file clean.
Furthermore if you use a macro such as INLINE which is defined as follows:
#ifdef DEBUG
#define INLINE
#else
#define INLINE inline
#endif
You can then include the inline file from the header in release and from the CPP in debug. This means that even if the compiler inlines functions in debug you won't have any difficulties when debugging. Admittedly, though, this isn't such a problem for compilers these days so you may want to skip doing this unless using an old compiler.
Generally speaking, a member function which has only one or two statements is probably best with its body written in the class declaration—especially if there are many of them. A member function with more than 20-50 statements is probably best not in the class declaration. For lengths and complexities between, it depends on many factors.
For example, having the function body in a class module helps prevent unnecessary recompiling of dependent modules when the class declaration does not change—only a member function body. This can greatly increase productivity when developing the class. Once the class is stable, this becomes much less important.