Multiple classes in one .cpp file - c++

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

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).

Scoping functions within namespace versus within class [duplicate]

This question already has answers here:
Namespace + functions versus static methods on a class
(9 answers)
Closed 3 years ago.
I've got a bunch of functions(func1(),func2(),...) in a header file to which I want to give some scope. I know of 2 implementations:
class bunchOfFunctions
{
public:
static void func1();
static void func2();
...
};
namespace bunchOfFunctions
{
void func1();
void func2();
...
};
In both the options, I can access the functions in the same way i.e. by bunchOfFunctions::func(). I prefer the namespace method(lesser typing), but I've seen the 1st method of implementation also at my workplace.
Which option is better? Is there any other option?
Apart from StroryTeller highlighted points,
Spread: A namespace can be spread into multiple files where as Class must be defined in a single place.
Readability and Understandability: Generally developers inherent understanding of what a Class is and what a namespace is.
"Better" depends on your definition for better. What qualities are you looking for in the scoping? There is no one size fits all answer here. But here are some properties of both approaches:
Necessity to qualify the function name.
With a class you must write bunchOfFunctions::func1() when
utilizing those functions. Meanwhile a namespace allows you to pull
a function in with a using declaration
using bunchOfFunctions::func1;
and use it unqualified in most scopes. If you wished you could even make all the members of the namespace available to unqualified name lookup with a using directive. Classes don't have an equivalent mechanic.
Aliasing.
There is no difference. To alias the class one writes
using BOF = bunchOfFunctions;
while aliasing the namespace is done with
namespace BOF = bunchOfFunctions;
Privacy.
A class can have private members. So you could put function declarations in there under a private access specifier and use them in public inline members. Namespaces have no such mechanism. Instead we rely on convention and put declarations under a "do not touch this" internal namespace, often called bunchOfFunctions::detail.
Argument dependent lookup.
C++ has a mechanism that allows it to find function declarations from an unqualified call, by examining the namespaces that contain the arguments to the call. For that to work, the function must be in an actual namespace. Static members of classes are not subject to such a lookup. So for any member types you may have, only a namespace will allow calls via ADL.
These four are off the top of my head. Judge your needs for yourself. As for "Is there any other option?", those are the only two ways you have to group such functions in C++ today. In C++20, we'll have modules! That will offer another level of grouping for code.
In addition the information given above I would add that going back to the standard definition of what a class and what a namespace is can help with decisions like this.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).
While these may sound similar they are rather specific. So if your functions are related, but not necessarily to the same object I would think hard about whether to put them in a class; particularly if grouping these functions together in a class may violate the Single Responsibility Principle: https://en.wikipedia.org/wiki/Single_responsibility_principle

Is defining auxiliary functions outside of an object allowed?

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.

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

Where to declare/define class scope constants in C++?

I'm curious about the benefits/detriments of different constant declaration and definition options in C++. For the longest time, I've just been declaring them at the top of the header file before the class definition:
//.h
const int MyConst = 10;
const string MyStrConst = "String";
class MyClass {
...
};
While this pollutes the global namespace (which I know is a bad thing, but have never found a laundry list of reasons why it is bad), the constants will still be scoped to individual translation units, so files that don't include this header won't have access to these constants. But you can get name collisions if other classes define a constant of the same name, which is arguably not a bad thing as it may be a good indication of an area that could be refactored.
Recently, I decided that it would be better to declare class specific constants inside of the class definition itself:
//.h
class MyClass {
public:
static const int MyConst = 10;
...
private:
static const string MyStrConst;
...
};
//.cpp
const string MyClass::MyStrConst = "String";
The visibility of the constant would be adjusted depending on whether the constant is used only internally to the class or is needed for other objects that use the class. This is what I'm thinking is the best option right now, mainly because you can keep internal class constants private to the class and any other classes using the public constants would have a more detailed reference to the source of the constant (e.g. MyClass::MyConst). It also won't pollute the global namespace. Though it does have the detriment of requiring non-integral initialization in the cpp file.
I've also considered moving the constants into their own header file and wrapping them in a namespace in case some other class needs the constants, but not the whole class definition.
Just looking for opinions and possibly other options I hadn't considered yet.
Your claim that declaring a non-integral constant as a static class member "have the detriment of requiring non-integral initialization in the cpp file" is not exactly solid, so to say. It does require a definition in cpp file, but it is not a "detriment", it is a matter of your intent. Namespace-level const object in C++ has internal linkage by default, meaning that in your original variant the declaration
const string MyStrConst = "String";
is equivalent to
static const string MyStrConst = "String";
i.e. it will define an independent MyStrConst object in every translation unit into which this header file is included. Are you aware of this? Was this your intent or not?
In any case, if you don't specifically need a separate object in every translation unit, the declaration of MyStrConst constant in your original example is not a good practice. Normally, you'd only put a non-defining declaration in the header file
extern const string MyStrConst;
and provide a definition in the cpp file
const string MyStrConst = "String";
thus making sure that the entire program uses the same constant object. In other words, when it comes to non-integral constants, a normal practice is to define them in cpp file. So, regardless of how you declare it (in the class or out) you will normally always have to deal with the "detriment" of having to define it in cpp file. Of course, as I said above, with namespace constants you can get away with what you have in your first variant, but that would be just an example of "lazy coding".
Anyway, I don't think there is a reason to over-complicate the issue: if the constant has an obvious "attachment" to the class, it should be declared as a class member.
P.S. Access specifiers (public, protected, private) don't control visibility of the name. They only control its accessibility. The name remains visible in any case.
Pollution of the global namespace is bad because someone (e.g. the writer of a library you use) might want to use the name MyConst for another purpose. This can lead to severe problems (libraries that can't be used together etc.)
Your second solution is clearly the best if the constants are linked to a single class. If that isn't so easy (think of physical or math constants without ties to a class in your program), the namespace solution is better than that. BTW: if you must be compatible to older C++ compilers, remember some of them can't use integral initialization in a header file - you must initialize in the C++ file or use the old enum trick in this case.
I think there are no better options for constants - at least can't think of one at the moment...
Polluting the global namespace should be self-evidently bad. If I include a header file, I don't want to encounter or debug name collisions with constants declared in that header. These types of errors are really frustrating and sometimes hard to diagnose. For example, I once had to link against a project that had this defined in a header:
#define read _read
If your constants are namespace pollution, this is namespace nuclear waste. The manifestation of this was a a series of very odd compiler errors complaining about missing the _read function, but only when linking against that library. We eventually renamed the read functions to something else, which isn't difficult but should be unnecessary.
Your second solution is very reasonable as it puts the variable into scope. There's no reason that this has to be associated with a class, and if I need to share constants among classes I'll declare constants in their own namespace and header file. This isn't great for compile-time, but sometimes it's necessary.
I've also seen people put constants into their own class, which can be implemented as a singleton. This to me seems work without reward, the language provides you some facilities for declaring constants.
You can declare them as globals in the c++ file, as long as they are not referenced in the header. Then they are private to that class and won't pollute the global namespace.
Personally I use your second approach; I've used it for years, and it works well for me.
From a visibility point I would tend to make the private constants file level statics as nobody outside the implementation file needs to know they exist; this helps prevent chain reaction recompiles if you need to change their names or add new ones as their name scope is the same as their usage scope...
If only one class is going to use these constants, declare them as static const inside the class body. If a bunch of related classes are going to use the constants, declare them either inside a class/struct that only holds the constants and utility methods or inside a dedicated namespace. For example,
namespace MyAppAudioConstants
{
//declare constants here
}
If they are constants used by the whole application (or substantial chunks of it), declare them inside a namespace in a header that is (either implicitly or explicitly) included everywhere.
namespace MyAppGlobalConstants
{
//declare constants here
}
don't pollute global namespace, pollute local.
namespace Space
{
const int Pint;
class Class {};
};
But practically...
class Class
{
static int Bar() {return 357;}
};