In my class in C++ I want to write a helper function (Which external users can't see or use) and found 2 ways to do that:
1) To declare it as private in the .h file and write the implementation in .cpp file.
2) To write the implementation directly in .cpp file without declaring it in the .h file.
What's the correct way, the difference or the advantage one have on the other?
Since you are not exposing this function through your interface, you should not declare it in the public header file. If you use it in a single cpp file, declare it in an anonymous namespace in that cpp file. If you use this function in multiple cpp files but you would still like to not make it a part of your interface, you can create internal header files that you #include in your source files, but aren't a part of your library's public interface.
The way is to create a class A that would be visible to the public, then create a descendant class B of this class and implement it privately. Then, when you are asked to create an A*, create a B* which is also an A* and return it. Your code sees a B* but the user of the class sees A* and may only access methods and variables declared in A. You also need to create/destroy your pointers with some function rather than with new/delete.
Pretty much like how COM implements IUnknown and stuff.
Related
I am a beginner in C++. I have a question regarding C++ design.
My file contains A,B,C,D,E class definitions. Class A contains the API which is used by other applications. I have defined this in a .h file. Classes B,C,D & E define concrete classes by inheriting an abstract class which is provided by some library. These definitions are not used by any external application, but only used by class A.
I have seen online that all the class definitions are provided in an .h file and the function implementations in a .cpp file. My question here is, even though class B,C,D & E definitions are not used externally by anyone, should I define them in the .h file? If I do define them there anyway, I cannot expose them to other applications, right?
If a class is only used locally in one module, you can declare it in the .cpp file. This is actually good practice; don't expose more than necessary.
In a case where you need to define a class (or function, etc.) in a header (for example, to share it between several related .cpp file) but you do not want to expose it publicly, you can have a separate, private header file which is only included in the relevant places, but is not made public. This can be hinted at by appending "private" to the header file name.
For now I do not use header files at all. Classes are each in a single .cpp file completely. But to save compile time I want to make use of header files now. My hope is that Visual Studio won't compile classes which weren't modified for debug builds then.
Is there a way to mention only public methods and members in the header file. In theory that would be enough information for the compiler. If another file, say main.cpp includes the class header there is no need for private methods and members, is it?
How can I use header files without retyping the names of private methods and members? The reasons for me to want so is coding productivity. When I want do add a small helper function to the class used by another method, I don't want to have to also add it's signature to the header file.
If another file, say main.cpp includes the class header there is no need for private methods and members, is it?
No, public methods and members aren't necessarily enough. For example, if another .cpp file were to try and create an instance of your class:
SomeClass instance;
the compiler will need to know, among other things, how much memory to allocate for SomeClass. For that it requires full knowledge of SomeClass's private data members.
The way you are framing the question makes it sound as if you were intent on fighting the language. I don't think that's a good way to go about it. I think the best way is to do things the way things are usually done in the language of your choice, and depart from that only when there is a specific, clearly understood need.
The way things are usually done in C++ is that the entire class declaration goes in the header file, and the definition is in some way split between the header file and the corresponding .cpp file. The exact split is determined by various technical considerations. For example, templates and inline functions normally have to appear in the header file. On the other hand, placing code in header files increases dependencies and potentially build times.
There are ways to address these issues. However, since this involves extra complexity, I'd argue that this should only be done if there is a clearly identifiable need.
I don't know of a way to do what you're asking, but there is another way to give some isolation. You might want to take a look at the pimpl idiom as it offers isolation about private information. It's a little bit of extra work, but it can be extremely useful, especially in large projects.
All function declarations should go in header files and all function definitions should go in cpp files. It's not good coding practice to put declarations inside the cpp files.
You could put definitions inside headers though, when you write templates or inline functions.
Once you declare the class in the header file, you have to declare all its methods and members inside the class' declaration in the header, given that your class is no longer declared in the cpp file.
I have a .cpp source file with some functions that need to be publicly accessible and some support functions that are only used in this source file.
I have been putting the all of these functions declarations in the header file as I personally find it useful to see everything a class offers in one place. However I would like to indicate whether the functions are for internal use, similar to the private access modifier, but without using classes (they are standalone functions).
Some possible solutions are:
Put the private declarations in the source file.
Put the private declarations in a separate header.
Both of these solutions split the public and private functions into separate files which I would like to avoid.
If the functions are not intended for public use, the shouldn't be placed into the header. Put them into the source file they are used in.
To completely hide these functions from being used outside the source file one of the following is usually done:
Functions are declared as static.
Functions are put into an unnamed namespace.
The latter is considered preferable. Actually, the C++ Standard 7.3.1.1 states:
The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.
For more discussion about unnamed namespaces vs static refer to Unnamed/anonymous namespaces vs. static functions and to corresponding comp.lang.c++.moderated thread.
If the private functions are only used in a single source file, then you don't need any extra header file. Just mark the functions either static or use an anonymous namespace.
If the functions can be used from many source files, declare them in a separate header file in a special namespace. That's my advice.
Where should support function declarations go?
They don't have to go anywhere. Make them static and keep them in source file. If they're only used in single source file, there's no need to put forward declarations into any header.
You don't mention whether these 'functions' are members of a class but I'll assume that they are. If so, I would recommend that you look at the 'pimpl idiom'. Basically this means putting all or most of what you want to keep private into a seperate class and then only having a pointer to an instance of the class in your class declaration. For example:
class MyClass
{
// ... some stuff
private:
SecretObject obj_;
int hiddenCall();
};
becomes
class MyClassImpl;
class MyClass
{
private:
MyClassImpl* impl_;
};
The idea then is that all the declaration and definition of your implemntation class would go into your .cpp file which hides it from anything but the compilation unit. This approach has a number of important advantages:
Hides implementation so the publicly available header does not give too much of the implementation away.
Can increase compilation speed by removing dependecies in the header - v. important if the header is included a lot.
Can be useful for 'insulating` client code against libraries that they shouldn't need to build against such as database APIs etc.
There are a number of drawbacks:
Can make unit testing more tricky if code is hidden away in cpp files. Personally I find a better solution is to have a seperate, private header and implementation file so you can control what clients of your code get but a test harness can still test it adequately. You can simply include the MyClassImpl header in your cpp file, but don't include it in the MyClass header - this would defeat the object.
The indirection between MyClass and MyClassImpl can be tiresome to code / manage.
Generally though, it's probably the best way of acheiving what you want to get to. Look at articles by Herb Sutter for a more in depth explaination.
On the other hand, if you are talking about free functions, not directly related to the class, then I would put these within the unnamed namespace within your cpp file. For example:
namespace {
// Your stuff goes here.
};
Again, you've got a unit test issue of how to access these functions if you take this approach, but it's possible to work around this if that's really an issue, perhaps by creating a specific namespace, conditional compilation etc. Not ideal, but possible.
In languages like Java, you can declare a class without a modifier so it will only be visible inside the same package. I need to do something similar in C++. I am trying to create an API that will be a library to be used in other applications. After asking this question on programmers Stackexchange, I have decided to use some sort of handle, which will just be an unsigned integer that is passed to an API function, which will then pass it to a class that will look it up in some sort of table and return a pointer to the object the handle represents, back to the function. The API function will then be allowed to operate on the pointer, but without the public ever having access to the pointer.
The problem is, I would like the class that handles the handles to not be visible to the public (even though the public won't have an instance of the class that contains the handles), as it is only needed inside the API functions. Also, I wanted this handle class to be a template (only needed for compiling the API), because I would most likely have handles representing different types of classes (although I could probably get away with one table containing void pointers, but it seems a little unsafe). I cant hide the class in a .cpp file, because it would be needed in multiple .cpp files that compose the API.
Also, I was thinking about using the pimpl idiom in any classes that have public functions, that way if there were any private functions in them that needed a parameter related to one of my classes hidden from the public, a header file including hidden classes would not need to be included with the API libraries for the API user to be able to compile the program.
So what would be the best way to hide classes that are only needed among other classes (spread across multiple .h and .cpp files) inside the API its self, from the outside world?
You can indeed use the PIMPL idiom; just write a forward declaration of the type and use a (smart) pointer to it as a member. That should take care of header files.
For the implementation, just have a separate header file that is included by the implementation of the library but not by any part of the interface. Example:
// Interface.h
class Secret;
class Hi {
public:
Hi();
~Hi();
void stuff();
private:
Secret* secret;
};
// Implementation.cpp
#include "Secret.h"
#include "Interface.h"
Hi::Hi() : secret(new Secret) { }
Hi::~Hi() { delete secret; }
void Hi::stuff() { secret->stuff(); }
// Secret.h
class Secret {
public:
int data;
void stuff() { ... }
};
You don't have to hide it specifically, just don't include the internal header in the .h files that define your API.
It is perfectly normal for a project to have internal helper classes and functions that are not part of the external interface. Compile them into your library, but don't distribute the headers.
This is probably not the best solution, especially if you need to use the class in multiple classes without a common ancestor, but you could use a private or protected nested class:
class Foo {
protected:
class SecretClass {
// ...
};
// ...
};
This is for C++.
Usually we have our function declaration in header file and definition in source file.
Say we have a class A with some functions:
//< A.hpp
class A
{
public:
virtual funcA();
virtual funcB();
}
And we want to have a class inherit from A and override its functions.
//< childA.hpp
class childA
{
virtual funcA();
virtual funcB();
}
Everytime we change the declarations of funcA() funcB(), we need to copy-and-paste the new declarations to the child classes header files. If the inheritance chain is long, it's quite bother.
I remember we don't have this problem with Object-C, do we?
You don't need to copy a member function declaration to the child class's header file unless you want to override it. In that case, I believe the main reason you're required to declare it is to inform anyone reading your header file that the child class is providing a different implementation. In principle, the compiler can figure it out automatically, but it could be a real pain for a human to do the same thing manually.
Note that in many cases, people reading your header files may not have access to the actual source code for the body (e.g., if it's a proprietary library that is delivered to them as compiled objects), so they can't just go look at the body to figure it out.
From the Objective-C article on Wikipedia:
Objective-C, like Smalltalk, can use dynamic typing: an object can be sent a message that is not specified in its interface.
http://en.wikipedia.org/wiki/Type_system#Dynamic_typing
C++, on the other hand, is statically typed. It's a stricter compile-time restraint.