I understand that static function declarations are done at the top of .cpp files such that I can use it only within that file and compiler would not complain if there are functions in other files with the same name. Is there an equivalent for classes? That is, declaring a "private" class used only within that file.
3 Answers
First, the C++ specification does not refer to source code files.
The relevant unit here is a translation unit, also called a compilation unit, and in practical terms it consists of all the source code resulting from preprocessing of an implementation file.
So you can have internal linkage (a.k.a. static
) functions in any kind of file. Although it doesn't make much practical sense to have them in a header file. Also, the placement in the code, whether first or last, does not matter.
An alternative to an internal linkage function like
static void foo() {}
is to place the function in an anonymous namespace, like
namespace {
void foo() {}
} // namespace <anon>
and you can do that also for a class.
Effectively this is equivalent to
namespace very_unique_autogenerated_name {
void foo() {}
}
// And in global namespace:
using namespace very_unique_autogenerated_name;
which means that you can refer to things in the anonymous namespace as if they were in the global namespace, and that you can have external linkage things there without their names colliding with other things in anonymous namespaces in other translation units.

- 142,714
- 15
- 209
- 331
XY problem? You can have classes with the same name in different files, unless you link them together. If your problem is that you have a name conflict, you can resolve that using namespaces:
//file1.cpp
namespace file1 {
class A { .. };
}
//file2.cpp
namespace file2 {
class A { .. }; //compiler won't complain
}

- 8,757
- 4
- 29
- 44
You can use unnamed namespaces for this:
namespace {
class A {};
}
There is more discussion at Unnamed/anonymous namespaces vs. static functions