What is the java "package private" equivalent in C++ ?
Java package privacy feature (where only classes within same package has visibility) is useful when providing APIs.
is there a similar feature for C++ (other than declaring other classes as "friend"s) ?
to elaborate more,
e.g. assume A.h and B.h are in same package (i.e. API lib)
File : A.h
class A
{
public :
void doA();
private :
int m_valueA;
};
File : B.h
class B
{
public :
void doB()
private:
int m_valueB;
}
What I want is,
public visibility : ONLY A::doA() and B::doB()
within package(i.e. API lib) : A should be able to access B::m_valueB and B should be able to access A::m_valueA.
WITHOUT making each other "friend" classes.
C++ has no equivalent to the Java concept of a "package". A package in Java is an arbitrary collection of code, defined only by being collected together into a bundle.
As such, "package private" kind of makes a mockery of the concept of encapsulation. Yes, the scope of access is "limited" to some degree, but it remains largely unbounded. So it's probably for the best that this isn't a natural feature of the language.
While C++ does not offer the concept of a "package", there are ways to allow specific arbitrary bundles of code to call functions which other arbitrary bundles of code cannot. This requires the use of a "key type" idiom.
A "key type" is a (usually empty) type whose main feature is that only certain code can create objects of that type. Any function taking such a type as a parameter therefore can only be called by code that is able to create the key type. The type therefore "unlocks" the function; hence the name.
The traditional use for this is to allow forwarding of private access through emplace and similar perfect forwarding constructs in C++. The key type's default constructor is made private, and the only people who can create it are explicit friends of the key type. But since the type is publicly copyable, any forwarding functions can copy them to the destination.
In your case, you want the key type to only be constructible from code in certain files. To do this, you simply have a header that provides a definition of the key type, typically as a simple empty class. In the public headers of your "package", any functions that you want to be "package private" will take a package_private as a const& parameter.
However, your public headers for the "package" do not include the definition of package_private; only a forward declaration of it. This means that code that only has access to the public headers are unable to create objects of that type. They can see the typename, but they cannot do anything with it.
So it might look like this:
//Internal header, included by all code in the "package"
struct package_private {};
inline constexpr static package_private priv; //Makes it easier to call these functions
//Header for library.
struct package_private;
void package_private_function(package_private const&, ...); //Must be `const&` to avoid needing to define `package_private`.
//To call the package private function inside the library:
package_private_function(priv, ...);
//This is a compile error for any code that doesn't have the internal header:
library::package_private priv{};
library::package_private_function(priv, ...);
C++ being C++, users can always cheat:
alignas(max_align_t) char data[sizeof(max_align_t)];
library::package_private &key = *reinterpret_cast<library::package_private*>(&data);
instance.pack_priv_function(key, ...);
This isn't even undefined behavior in C++20, so long as package_private is within the given alignment and size of data and it is an implicit lifetime type. You could do things that force package_private to not be these things, but that only renders this code UB. It will still compile and almost certainly still work; after all, the function isn't ever accessing this object.
The traditional way to hint to users that some type in a header is internal and shouldn't be used by external code is to stick it in a detail namespace.
C++20 modules provides a way to prevent a category of ways to subvert this. If we consider a module to be a "package", all you have to do is not export the package_private type. It can still be listed as parameters of functions that do get exported (and they no longer need to be const&). But the package_private type itself isn't exported.
Code within the module can use the name; you can put the definition into an implementation partition that gets imported by any in-module files that need this access. But code outside of the module which imports it can't use that name, so they can't even do the casting trick shown above. There are metaprogramming techniques that can inspect a function's signature without knowing its types, but those are really hard and are spoiled by overloading.
Then again, Java reflection can break any encapsulation, so it's not like "package private" is fool-proof.
c++ doesn't have packages as in java. But it does have namespaces, however namespaces is just that, a namespace. So it is a different beast.
A somewhat emulation could in some situations be an inner classes (classes within other classes) - since inner classes are considered members.
Besides that, there are header files and implementation(.cpp files) - in that sense you have units or modules that control what is actual visible (not just private but completely hidden - in particular if put into anon. namespace). This concept covers both just a single .h file and .cpp file or entire projects/libs/dlls that is more like a full package (and can choose what parts of API they expose through what gets 'shown' in their respective header files).
You might be interested in the PIMPL idiom in C++, which, as #darune said, is not equivalent but close in semantic. Typically, you'll do this:
In YourPublicClass.hpp
class MyPublicClass
{
// Public interface
public:
void doSomething();
void manipulatePrivateStuff(Stuff * stuff);
MyPublicClass(...);
~MyPublicClass();
struct Stuff; // <= This is were the magic happens, this stuff
// is unknown/private from who include this header
private:
Stuff * _member;
};
In YourPublicClass.cpp
#include <iostream>
#include "YourPublicClass.hpp"
struct MyPublicClass::Stuff
{
// Public members that are only accessible from this compilation unit
// but private from the rest of the code, like a private package
int a;
void explodeInTenSeconds() { if (!a--) std::cout<<"Boom!"<<std::endl; }
Stuff(int delay = 10) : a(delay) {}
};
void MyPublicClass::doSomething() { _member->explodeInTenSeconds(); }
void MyPublicClass::manipulatePrivateStuff(Stuff * stuff) { stuff->a = 10; }
MyPublicClass::MyPublicClass(...) : _member(new Stuff(10)) {}
MyPublicClass::~MyPublicClass() { delete(_member); }
If you need another class to access the "package private" Stuff, you'll to move the MyPublicClass::Stuff declaration to its own header and include that header in this class's definition file (.cpp). This header shouldn't be included outside of your "package", it's not public. It's not required to be manipulated, the compiler is perfectly fine with only knowing it's a pointer to a unspecified structure.
C++ doesn't have packages.
The consequence is that the requested behavior "different access for other code inside my package from code outside my package" isn't even meaningful. There is no "code inside my package" because there is no "my package".
Elaborating one step farther, the C++ private access modifier meets the specification of Java package private. It's inaccessible (private) for code outside the package, just like Java package private. And it is trivially accessible to code inside the same package --- because there is no such code.
Obviously that's not useful for establishing collaboration. But it's what you get when you try to ask questions about C++ that are only meaningful in some other language. Another aspect of your question that is Java-centric and harmful for thinking about C++, is that you consider all code to be organized into classes. In C++ that isn't so, there are free functions and associated (by ADL) functions which are not class members.
Firstly, It is important to understand what private-package is. It means that other members of the same package have access to the item. A package in java is an arbitrary collection of code which is defined only by being collected in bundle.
This feature of "private-package" in C++ has not equivalent to the java language.
Related
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.
In my company's C++ codebase I see a lot of classes defined like this:
// FooApi.h
class FooApi {
public:
virtual void someFunction() = 0;
virtual void someOtherFunction() = 0;
// etc.
};
// Foo.h
class Foo : public FooApi {
public:
virtual void someFunction();
virtual void someOtherFunction();
};
Foo is this only class that inherits from FooApi and functions that take or return pointers to Foo objects use FooApi * instead. It seems to mainly be used for singleton classes.
Is this a common, named way to write C++ code? And what is the point in it? I don't see how having a separate, pure abstract class that just defines the class's interface is useful.
Edit[0]: Sorry, just to clarify, there is only one class deriving from FooApi and no intention to add others later.
Edit[1]: I understand the point of abstraction and inheritance in general but not this particular usage of inheritance.
The only reason that I can see why they would do this is for encapsulation purposes. The point here is that most other code in the code-base only requires inclusion of the "FooApi.h" / "BarApi.h" / "QuxxApi.h" headers. Only the parts of the code that create Foo objects would actually need to include the "Foo.h" header (and link with the object-file containing the definition of the class' functions). And for singletons, the only place where you would normally create a Foo object is in the "Foo.cpp" file (e.g., as a local static variable within a static member function of the Foo class, or something similar).
This is similar to using forward-declarations to avoid including the header that contains the actual class declaration. But when using forward-declarations, you still need to eventually include the header in order to be able to call any of the member functions. But when using this "abstract + actual" class pattern, you don't even need to include the "Foo.h" header to be able to call the member functions of FooApi.
In other words, this pattern provides very strong encapsulation of the Foo class' implementation (and complete declaration). You get roughly the same benefits as from using the Compiler Firewall idiom. Here is another interesting read on those issues.
I don't know the name of that pattern. It is not very common compared to the other two patterns I just mentioned (compiler firewall and forward declarations). This is probably because this method has quite a bit more run-time overhead than the other two methods.
This is for if the code is later added on to. Lets say NewFoo also extends/implements FooApi. All the current infrastructure will work with both Foo and NewFoo.
It's likely that this has been done for the same reason that pImpl ("pointer to implementation idiom", sometimes called "private implementation idiom") is used - to keep private implementation details out of the header, which means common build systems like make that use file timestamps to trigger code recompilation will not rebuild client code when only implementation has changed. Instead, the object containing the new implementation can be linked against existing client object(s), and indeed if the implementation is distributed in a shared object (aka dynamic link library / DLL) the client application can pick up a changed implementation library the next time it runs (or does a dlopen() or equivalent if it's linking at run-time). As well as facilitating distribution of updated implementation, it can reduce rebuilding times allowing a faster edit/test/edit/... cycle.
The cost of this is that implementations have to be accessed through out-of-line virtual dispatch, so there's a performance hit. This is typically insignificant, but if a trivial function like a get-int-member is called millions of times in a performance critical loop it may be of interest - each call can easily be an order of magnitude slower than inlined member access.
What's the "name" for it? Well, if you say you're using an "interface" most people will get the general idea. That term's a bit vague in C++, as some people use it whenever a base class has virtual methods, others expect that the base will be abstract, lack data members and/or private member functions and/or function definitions (other than the virtual destructor's). Expectations around the term "interface" are sometimes - for better or worse - influenced by Java's language keyword, which restricts the interface class to being abstract, containing no static methods or function definitions, with all functions being public, and only const final data members.
None of the well-known Gang of Four Design Patterns correspond to the usage you cite, and while doubtless lots of people have published (web- or otherwise) corresponding "patterns", they're probably not widely enough used (with the same meaning!) to be less confusing than "interface".
FooApi is a virtual base class, it provides the interface for concrete implementations (Foo).
The point is you can implement functionality in terms of FooApi and create multiple implementations that satisfy its interface and still work with your functionality. You see some advantage when you have multiple descendants - the functionality can work with multiple implementations. One might implement a different type of Foo or for a different platform.
Re-reading my answer, I don't think I should talk about OO ever again.
I want to make a class-library using pimpl idiom, so that I can hide my implementation details for the user of the library.
Is it possible, to make a class, where some methods are public and callable from users perspective, while having methods that are only callable from the internals.
Right now I only see a solution with the friend keyword and declaring the internal methods private.
For example:
MyPartiallyVisibleClass: Class containing a mixture of methods accessible to the user, and methods only accessible to the internals of library.
InternalClass: Class internally in the library. The user will never know this excist.
// MyPartiallyVisibleClass.h: Will be included by the user.
class MyPartiallyVisibleClass
{
private:
class Impl; // Forward declare the implementation
Impl* pimpl;
InternalMethod(); // Can only be called from within the library-internals.
public:
UserMethod(); // Will be visible and callable from users perspective.
}
// MyPartiallyVisibleClass.cpp
class MyPartiallyVisibleClass::Impl
{
private:
InternalMethod();
public:
UserMethod();
friend class InternalClass;
}
// Internal class that will not be included into users application.
class InternalClass
{
public:
InternalMethod()
{
MyPartiallyVisibleClass pvc;
pvc.InternalMethod();
}
}
Is there a better way of doing this?
There are pros and cons.
By a source stand point, if you distribute only headers and binaries, everything in in cpp files will not be seen by the source user.
So, also MyPartiallyVisibleClass::Impl::Usermethod is not visible, but being public, callable everywhere in the cpp file it is declared.
Zero way, one way or two way friendship between external and internal class can be required if you don't want to repeat external methods internally. It can seem an encapsulation break, but it is not, since the "capsule" here, is the external class. Creating complex hierarchy of intenal privacy (public external, private external, public internal private internal public even more internal ... etc.) can become clueless if everything goes under your same responsibility. Unless the internal part is so large to be assigned to different developers, so that another level of interface & implementation is needed.
By a binary user standpoint, however, every function that is not inlined exist, and -having external linkage- its name is available into the library, and hence it is "callable" by writing another header that makes it publicly available to other sources. I will just be an undocumented feature.
The concept of public/private etc. is for code safety (avoid function you don't want to promise to maintain with always the same "contract" to be available, thus making external code more stable, eliminating unwanted dependency) not for "security" (avoid who wants to call to find a way to call).
There is then also another drawback: templates cannot be hidden into sources, since they have to be expanded into the users's source code space (not the developer binary space). And the growing of generic programming, functional static polimorphism etc. makes the pimpl idiom less and less attractive.
There are today many programs made by a single cpp file that instantiate a single "manager object" whose entire functionality reside as is made of header only libraries. Believing or not, this way to program makes code even more portable between compilers, since it doesn't have to exist in a different binary form for every possible client compiler. And does not necessarily make build time longer: precompiled header can be generated once for code that don't change too often. Who cares is the user ca see the code? If he wants to use it and be supported is not his interest to change it improperly. If he wants to hack or stole, he will find anyway another way to do it.
I'm working on a sound library (with OpenAL), and taking inspiration from the interface provided by FMOD, you can see the interface at this link.
I've provided some concepts like: Sound, Channel and ChannelGroup, as you can see through FMOD interface, all of those classes have a private constructor and, for example, if you would create a Sound you mast use the function createSound() provided by the System class (the same if you would create a Channel or a ChannelGroup).
I'd like to provide a similar mechanism, but I don't understand how it work behind. For example, how can the function createSound() create a new istance of a Sound? The constructor is private and from the Sound interface there aren't any static methods or friendship. Are used some patterns?
EDIT: Just to make OP's question clear, s/he is not asking how to create a instance of class with private constructor, The question is in the link posted, how is instance of classes created which have private constructor and NO static methods or friend functions.
Thanks.
Hard to say without seeing the source code. Seems however that FMOD is 100% C with global variables and with a bad "OOP" C++ wrapper around it.
Given the absence of source code and a few of the bad tricks that are played in the .h files may be the code is compiled using a different header file and then just happens to work (even if it's clearly non-standard) with the compilers they are using.
My guess is that the real (unpublished) source code for the C++ wrapper is defining a static method or alternatively if everything is indeed just global then the object is not really even created and tricks are being played to fool C++ object system to think there is indeed an object. Apparently all dispatching is static so this (while not formally legal) can happen to work anyway with C++ implementations I know.
Whatever they did it's quite ugly and non-conforming from a C++ point of view.
They never create any instances! The factory function is right there in the header
/*
FMOD System factory functions.
*/
inline FMOD_RESULT System_Create(System **system)
{ return FMOD_System_Create((FMOD_SYSTEM **)system); }
The pointer you pass in to get a System object is immediately cast to a pointer to a C struct declared in the fmod.h header.
As it is a class without any data members who can tell the difference?
struct Foo {
enum Type {
ALPHA,
BETA_X,
BETA_Y
};
Type type () const;
static Foo alpha (int i) {return Foo (ALPHA, i);}
static Foo beta (int i) {return Foo (i<0 ? BETA_X : BETA_Y, i);}
private:
Foo (Type, int);
};
create_alpha could have been a free function declared friend but that's just polluting the namespace.
I'm afraid I can't access that link but another way could be a factory pattern. I'm guessing a bit, now.
It is the factory pattern - as their comment says.
/*
FMOD System factory functions.
*/
inline FMOD_RESULT System_Create(System **system) { return FMOD_System_Create((FMOD_SYSTEM **)system); }
It's difficult to say exactly what is happening as they don't publish the source for the FMOD_System_Create method.
The factory pattern is a mechanism for creating an object but the (sub)class produced depends on the parameters of the factory call. http://en.wikipedia.org/wiki/Factory_method_pattern
As I understand, the pimpl idiom is exists only because C++ forces you to place all the private class members in the header. If the header were to contain only the public interface, theoretically, any change in class implementation would not have necessitated a recompile for the rest of the program.
What I want to know is why C++ is not designed to allow such a convenience. Why does it demand at all for the private parts of a class to be openly displayed in the header (no pun intended)?
This has to do with the size of the object. The h file is used, among other things, to determine the size of the object. If the private members are not given in it, then you would not know how large an object to new.
You can simulate, however, your desired behavior by the following:
class MyClass
{
public:
// public stuff
private:
#include "MyClassPrivate.h"
};
This does not enforce the behavior, but it gets the private stuff out of the .h file.
On the down side, this adds another file to maintain.
Also, in visual studio, the intellisense does not work for the private members - this could be a plus or a minus.
I think there is a confusion here. The problem is not about headers. Headers don't do anything (they are just ways to include common bits of source text among several source-code files).
The problem, as much as there is one, is that class declarations in C++ have to define everything, public and private, that an instance needs to have in order to work. (The same is true of Java, but the way reference to externally-compiled classes works makes the use of anything like shared headers unnecessary.)
It is in the nature of common Object-Oriented Technologies (not just the C++ one) that someone needs to know the concrete class that is used and how to use its constructor to deliver an implementation, even if you are using only the public parts. The device in (3, below) hides it. The practice in (1, below) separates the concerns, whether you do (3) or not.
Use abstract classes that define only the public parts, mainly methods, and let the implementation class inherit from that abstract class. So, using the usual convention for headers, there is an abstract.hpp that is shared around. There is also an implementation.hpp that declares the inherited class and that is only passed around to the modules that implement methods of the implementation. The implementation.hpp file will #include "abstract.hpp" for use in the class declaration it makes, so that there is a single maintenance point for the declaration of the abstracted interface.
Now, if you want to enforce hiding of the implementation class declaration, you need to have some way of requesting construction of a concrete instance without possessing the specific, complete class declaration: you can't use new and you can't use local instances. (You can delete though.) Introduction of helper functions (including methods on other classes that deliver references to class instances) is the substitute.
Along with or as part of the header file that is used as the shared definition for the abstract class/interface, include function signatures for external helper functions. These function should be implemented in modules that are part of the specific class implementations (so they see the full class declaration and can exercise the constructor). The signature of the helper function is probably much like that of the constructor, but it returns an instance reference as a result (This constructor proxy can return a NULL pointer and it can even throw exceptions if you like that sort of thing). The helper function constructs a particular implementation instance and returns it cast as a reference to an instance of the abstract class.
Mission accomplished.
Oh, and recompilation and relinking should work the way you want, avoiding recompilation of calling modules when only the implementation changes (since the calling module no longer does any storage allocations for the implementations).
You're all ignoring the point of the question -
Why must the developer type out the PIMPL code?
For me, the best answer I can come up with is that we don't have a good way to express C++ code that allows you to operate on it. For instance, compile-time (or pre-processor, or whatever) reflection or a code DOM.
C++ badly needs one or both of these to be available to a developer to do meta-programming.
Then you could write something like this in your public MyClass.h:
#pragma pimpl(MyClass_private.hpp)
And then write your own, really quite trivial wrapper generator.
Someone will have a much more verbose answer than I, but the quick response is two-fold: the compiler needs to know all the members of a struct to determine the storage space requirements, and the compiler needs to know the ordering of those members to generate offsets in a deterministic way.
The language is already fairly complicated; I think a mechanism to split the definitions of structured data across the code would be a bit of a calamity.
Typically, I've always seen policy classes used to define implementation behavior in a Pimpl-manner. I think there are some added benefits of using a policy pattern -- easier to interchange implementations, can easily combine multiple partial implementations into a single unit which allow you to break up the implementation code into functional, reusable units, etc.
May be because the size of the class is required when passing its instance by values, aggregating it in other classes, etc ?
If C++ did not support value semantics, it would have been fine, but it does.
Yes, but...
You need to read Stroustrup's "Design and Evolution of C++" book. It would have inhibited the uptake of C++.