Global object of a class with private constructor - c++

Is it possible to somehow declare the global scope as a friend of a class?
The problem I am facing is the following:
class Foo
{
Foo() {}
};
Foo foo; //error: 'Foo::Foo()' is private
So, what I want is to be able to declare an object of Foo at the global scope but not anywhere else.
Note that this question is purely out of interest, I'm not trying to solve an actual problem.

No, it's not possible to do that. You can only name specific classes or functions as friends. It's not possible to make a namespace including the global namespace a friend.
I think the reason there isn't a good work around is that when you define a class or function, only one definition is allowed (not considering overloads, which are really different functions). But, you are allowed to open a namespace as many times as you want and append extra stuff into it each time. So, if you allowed access to a particular namespace, anybody who wanted to could type:
namespace TheNamesapceWithAccess
{
// I've got access to it here too as well as
// to the original namespace definition that was
// the only one that was intended to be allowed access.
// And I could define a function here that allows access the private thing
// from outside this namespace. I've just subverted the access restriction
// you intended.
}

Related

Clarification on classes and scopes in this scenario

I'm currently working with the JUCE Framework to create an audio VST plugin to get to grips and learn, but just want to clarify some basic stuff relating to classes.
in my header file, i have a class EQPLUGProcessor and inside that class i call static juce::AudioProcessorValueTreeState::ParameterLayout createParameterLayout();
When i call the function createParameterLayout() in my .cpp i have to write juce::AudioProcessorValueTreeState::ParameterLayout EQPLUGAudioProcessor::createParameterLayout(){}
My question is, why do i have to include the juce::AudioProcessorValueTreeState::ParameterLayout before the actual scope that the function is in ( EQPLUGAudioProcessor)? Surely i should be telling the compiler to look in the EQPLUGAudioProcessor and thats it?
I get that EQPLUGAudioProcessor is the class which its all inside, but still cant seem to understand when, where and why i'd need to clarify the classes that the function comes from again in the .cpp?
Let me know if this requires clarification.
An enclosing namespace or a class does not have to be specified only inside the same namespace or a class:
class store {
class give_me {
// ...
};
static give_me something_cool();
};
Here, the declaration of something_cool() only needs to reference give_me, rather than store::give_me. This is because this declaration appears inside the declaration of its class.
Now that this class is declared, and it's time to define it's class method, everything must be spelled out:
store::give_me store::something_cool()
{
// ...
}
If the class method returned a void instead you'l still have to write something like:
void store::something_cool()
{
// ...
}
You already understand that you can't just write void something_cool() and define this class method. This would only define some unrelated function with this name.
You have to write store::something_cool because this definition no longer appears within the store scope.
Well, the same thing applies not just to class methods but also to inner classes (and also other kinds of symbols that are declared in some enclosing scope). Since give_me is not a class that's declared in global scope, it is an inner class, when in global scope you must reference it as store::give_me.
That's just how C++ works. There are also various complicated rules that define where a scope begins, and ends, with respect to C++'s syntax, that's tangentially related to this. In some cases it is possible to take advantage of these scoping rules and avoding explicit scope references by using an auto declaration with a trailing return type; but how to do that will have to be a different question for some other time.

Hiding free functions

Lets say I have a bunch of free functions, within a particular namespace, which are covered by unit-tests. And lets say I see some common functionality that can be moved out into a separate free function. What can I do such that this new function becomes hidden? In other words, this function should only be used by the aforementioned free functions and not elsewhere. Should I added it to a namespace under the free functions' namespace. If so, what should I call the namespace - is there a naming convention?
I should also point out that this new function is not unit tested since it is used internally by other functions that are unit-tested. Perhaps I'm being lazy and the solution to this question is that I simply unit-test this function also and then people can use it if they want.
You can hide it: make it a private static member function of a class, and then explicitly friend each of your inline functions. The implementation could be in- or out-of-line, access control will still work.
Unless you need to restrict access though, I'd follow the Boost convention and just put it in a nested namespace called detail (or something similar).
This is just intended to document that it is an implementation detail, rather than a stable public interface (and to avoid polluting the namespace, of course).
This also avoids having to explicitly list each free function as a friend.
You could have the helper function as a static function in the private section of a class and then only friend the functions that are allowed to use it.
class Foo
{
static int helper() {return 0;}
friend void baz();
};
void baz()
{
Foo::helper(); //compiles
}
void buz()
{
Foo::helper(); //doesn't compile
}

Unnamed namespaces vs private variables

I have been reading through other questions on here and there is something that has me confused and hopefully it can be explained. I am sure there it is a simple thing but it is alluding me.
So in C++ we have private variables that are only viewable within the class:
class MyClass
{
private:
int i;
};
But we can also have unnamed namespaces:
namespace
{
int i;
}
Both appear to be private to the class but in the 2nd case you cannot see they exist from the header file. From reading other questions it seems that functions are different as you can't pass class objects to them? But I am not sure what the difference is here for variables.
Is there a disadvantage to the 2nd way that means you should still use private variables?
They aren't the same.
Integer i in the anonymous namespace will be shared by all instances of MyClass.
The private integer i in MyClass will be unique for each instantiation of the class.
The equivalent using private would be to make i static:
//.h
class MyClass
{
private:
static int i;
};
And instantiate the one single shared i like this:
//.cpp
int MyClass::i = 0;
Both appear to be private to the class ...
No, only the first is private to the class. It's a non-static member variable; one is instantiated in every object of the class type.
The second is not in a class at all; it has static storage duration, so one is instantiated for the whole program. Anything that accesses it is accessing the same variable as anything else that accesses it. Being in an unnamed namespace, it's only accessible within the translation unit (i.e. the source file) that defines it; but it's accessible to any code there, not just a particular class.
Is there a disadvantage to the 2nd way that means you should still use private variables?
If you want a copy of the variable in each class object, then you need it to be a non-static member.
If you want to share it between all objects, then it's up to you whether to make it a static member, or put it in a namespace inside the class's implementation file. I often do the latter to simplify the class definition. Disadvantages are that access isn't restricted just to the class but to anything else in that file, and you can't access it from any code that you might want to put in the header.
Namespaces are unrelated to objects/classes. In particular, if you have two objects, each has its own copy of a private variable.
They are quite different concepts. The private data member is visible only to a class, and in the non-static case, each class instance owns one of these. The anonymous namespace allows you to make code available only to other code in the same file. So in the case of the single int variable, all code defined in the same place as the anonymous namespace would see the same, single variable.

C++, static vs. namespace vs. singleton

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

Prevent creation of class whose member functions are all static

All the member variables and member functions in my class ClassA are static.
If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user from trying to create an object of this class.
Would it be enough to create a private default (no variables) constructor? Or do I have to also create private copy constructor and private assignment operator (to prevent using the default constructors)? And if I do have to create them too, maybe it would be better just to create some dummy pure virtual function instead, and this will prevent the user from creating an object?
Thank you
Instead of using a class with all static methods, you may be better off making the methods free-standing functions in a separate namespace. The call syntax would be the same:
namespace::function() instead of classname::function()
and you don't need to deal with someone trying to instantiate your class.
Creating a private default constructor should be sufficient. Both of the other default constructs (copy constructor and assignment) rely on having an instance to work correctly. If there is no default constructor then there is no way to create an instance, hence no way to actually get to the copy construction part.
It would likely save you a few headaches though to define all 3 as private and not implemented.
Like others said, a namespace is what you should use. If you want to stay with your class, create a class that has a private constructor, and derive from it, to make your intention obvious:
class NonConstructible {
NonConstructible();
};
class SuperUtils: NonConstructible {
static void foo();
// ...
static std::vector<int> globalIDs;
// ...
};
Ok, now let's look into the namespace which are the one and only way to do this:
namespace SuperUtils {
void foo() {
// ....
}
std::vector<int> globalIDs;
};
You can call that using SuperUtils::foo(); in both cases, but the namespace has the advantage that in a scope you can use the namespace declaration and directive to bring certain or all members into the current scope, so that you can reference them without using SuperUtils:::
void superFunction() {
using namespace SuperUtils;
foo();
}
While generally that should be avoided, it can be helpful when the method is using exclusively much stuff from SuperUtils, which then can improve the readability of the code.
In order to use a copy constructor you have to have an object to copy, so if you've locked down the default constructor you should be safe.
The best way to prevent creation of non-heap objects is to make destructor private. Then there is no way compiler can destruct the object when it goes out of scope and it will complain.
This will not prevent anyone from doing new however.