Function Proto-typing - c++

What is the best use of function proto-typing in c++?
For instance I understand you can use it to place functions below the scope of your 'main' function. When is this considered useful?
I always like to have my main at the bottom of the main file as a personal preference.
I do not have a whole lot of experience with C++ and trying to get better with it.
I did notice that it seems to have a quicker execution time if you do not proto type.

By far the most useful effect of having function prototypes is that you don't need to put all your function definitions in their respective headers. If this was the case, compile time would go through the roof!
Another important case where it's necessary is when two function implementations have a cyclical dependency on one another. Putting these cyclical dependent definitions after both functions have been declared makes this possible. This is sometimes necessary even for function templates.

Related

forcing a function to be pure

In C++ it is possible to declare that a function is const, which means, as far as I understand, that the compiler ensures the function does not modify the object. Is there something analogous in C++ where I can require that a function is pure? If not in C++, is there a language where one can make this requirement?
If this is not possible, why is it possible to require functions to be const but not require them to be pure? What makes these requirements different?
For clarity, by pure I want there to be no side effects and no use of variables other than those passed into the function. As a result there should be no file reading or system calls etc.
Here is a clearer definition of side effects:
No modification to files on the computer that the program is run on and no modification to variables with scope outside the function. No information is used to compute the function other than variables passed into it. Running the function should return the same thing every time it is run.
NOTE: I did some more research and encountered pure script
(Thanks for jarod42's comment)
Based on a quick read of the wikipedia article I am under the impression you can require functions be pure in pure script, however I am not completely sure.
Short answer: No. There is no equivalent keyword called pure that constrains a function like const does.
However, if you have a specific global variable you'd like to remain untouched, you do have the option of static type myVar. This will require that only functions in that file will be able to use it, and nothing outside of that file. That means any function outside that file will be constrained to leave it alone.
As to "side effects", I will break each of them down so you know what options you have:
No modification to files on the computer that the program is run on.
You can't constrain a function to do this that I'm aware. C++ just doesn't offer a way to constrain a function like this. You can, however, design a function to not modify any files, if you like.
No modification to variables with scope outside the function.
Globals are the only variables you can modify outside a function's scope that I'm aware of, besides anything passed by pointer or reference as a parameter. Globals have the option of being constant or static, which will keep you from modifying them, but, beyond that, there's really nothing you can do that I'm aware.
No information is used to compute the function other than variables passed into it.
Again, you can't constrain it to do so that I'm aware. However, you can design the function to work like this if you want.
Running the function should return the same thing every time it is run.
I'm not sure I understand why you want to constrain a function like this, but no. Not that I'm aware. Again, you can design it like this if you like, though.
As to why C++ doesn't offer an option like this? I'm guessing reusability. It appears that you have a specific list of things you don't want your function to do. However, the likelihood that a lot of other C++ users as a whole will need this particular set of constraints often is very small. Maybe they need one or two at a time, but not all at once. It doesn't seem like it would be worth the trouble to add it.
The same, however, cannot be said about const. const is used all the time, especially in parameter lists. This is to keep data from getting modified if it's passed by reference, or something. Thus, the compiler needs to know what functions modify the object. It uses const in the function declaration to keep track of this. Otherwise, it would have no way of knowing. However, with using const, it's quite simple. It can just constrain the object to only use functions that guarantee that it remains constant, or uses the const keyword in the declaration if the function.
Thus, const get's a lot of reuse.
Currently, C++ does not have a mechanism to ensure that a function has "no side effects and no use of variables other than those passed into the function." You can only force yourself to write pure functions, as mentioned by Jack Bashford. The compiler can't check this for you.
There is a proposal (N3744 Proposing [[pure]]). Here you can see that GCC and Clang already support __attribute__((pure)). Maybe it will be standardized in some form in the future revisions of C++.
In C++ it is possible to declare that a function is const, which means, as far as I understand, that the compiler ensures the function does not modify the object.
Not quite. The compiler will allow the object to be modified by (potentially ill-advised) use of const_cast. So the compiler only ensures that the function does not accidentally modify the object.
What makes these requirements [constant and pure] different?
They are different because one affects correct functionality while the other does not.
Suppose C is a container and you are iterating over its contents. At some point within the loop, perhaps you need to call a function that takes C as a parameter. If that function were to clear() the container, your loop will likely crash. Sure, you could build a loop that can handle that, but the point is that there are times when a caller needs assurance that the rug will not be pulled out from under it. Hence the ability to mark things const. If you pass C as a constant reference to a function, that function is promising to not modify C. This promise provides the needed assurance (even though, as I mentioned above, the promise can be broken).
I am not aware of a case where use of a non-pure function could similarly cause a program to crash. If there is no use for something, why complicate the language with it? If you can come up with a good use-case, maybe it is something to consider for a future revision of the language.
(Knowing that a function is pure could help a compiler optimize code. As far as I know, it's been left up to each compiler to define how to flag that, as it does not affect functionality.)

What exactly is a forward declaration with respect to memory?

I understand on a high level what a function declaration does: you declare them at the top of your file so the compiler will know which functions you are calling. However, what does the compiler exactly do with it? I know that functions are written in the text section of memory and expects arguments to be given by a register on the stack. Are function prototypes also placed within the text? Or are forward declarations simply indicators for the linkage editor to use to connect all the files together, and they are "removed" in the final product? Or does the compiler do something else with them?
I have looked around online and could not find a good resource, so if any of you can answer this or give me a resource outlining this specific phenomena, that would be greatly appreciated!
EDIT
I think there was a misunderstanding in the question, which is my mistake. My question was on how exactly does the C-compiler utilize the forward declarations. It seems from the answers below, it is used during the conversion of c-code to assembly. Is this correct?
A function prototype is simply a way to notify the compiler about how the function should be called, without having to provide any details on the implementation.
All a caller needs to know is how to call it: what parameters to pass and what to expect back.
Everything else should be hidden as much as possible so as to allow proper encapsulation, the ability for a function to change however it wants internally, without breaking anyone currently using it.
By way of example, here's a function prototype used for storing key-value pairs (both strings):
enum kvpErr kvpAdd (char *key, char *value);
This allows the compiler to ensure that you actually pass in two C strings and take an integral error code back. But it reveals nothing about the internals of the function. It may use various forms of balanced trees, a dynamically allocated array, a connection to an SQL database or a text file on an NFS server located in Outer Mongolia.
The bottom line is, you can improve the implementation in any way you wish as long as the function signature itself is kept identical.

class forward declaration

Can I use forward declaration for a class in order to put it's definition and Implementation later in the program after it's been used (similar to what is done about functions)?
(I need to join multiple source files of a program into a file, and i want to put the classes' definitions and Implementations at the end of the file in order to main be at the top of the file.)
Yes you can, to a certain extent.
You have to realize that the C++ compiler is quite stupid, and doesn't read ahead. This is the reason why you have to use function prototypes (among some other reasons).
Now, a function isn't hard for compiler to resolve. It just looks at the return type of the function, and the types of the parameters of the function, and just assumes that the function is there, without any knowledge about what's actually inside the function, because it ultimately doesn't matter at that point.
However, the contents of the class do matter (the compiler needs to know the size of the class for example). But remember about the not reading ahead bit? When you forward define a class, the compiler doesn't know about what's in it, and therefore is missing a lot of information about it. How much space does is need to reserve for example?
Therefore, you can forward define classes, but you can't use them as value types. The only thing you can do with it (before it has been concretely declared), is use pointers to it (and use it as a function return type and template argument, as pointer out by
#Cheersandhth.-Alf).
If the thing you need to use isn't a pointer, you should probably use headers (read this if you want to learn more about that).
Without a class definition somewhere earlier, you can't use any class members, nor can you create any instances, but you can
use T* and T& types,
use T for formal return type and parameter declarations (yes even by value),
use T as a template parameter,
and possibly more, but the above is what occurred to me immediately.
So if that's all you need, then you're set to go with the forward-declarations.
However, all that the forward declaring buys you in the sketched situation is added work, maintaining the same code in two places, so it's difficult to see the point of it…
Oh, I just remembered, there is a particularly nasty Undefined Behavior associated with forward-declared incomplete types, namely using delete p where p is a pointer to incomplete type. This requires the destructor to be trivial. If the compiler is good then it warns, but don't count on it.
In summary, I would just place main at the very end of that code, where it belongs, avoiding all the problems.

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.

Class member function declaration doubt

I'm reading a C++ tutorial and I've ran into this sentence:
The only difference between defining a class member function
completely within its class or to include only the prototype and later
its definition, is that in the first case the function will
automatically be considered an inline member function by the compiler,
while in the second it will be a normal (not-inline) class member
function, which in fact supposes no difference in behavior.
I know what an inline function is, my doubt is about which style to choose. Should I define every function inside its class or outside? Perhaps the simplest functions inside and the other outside?
I fear that defining every function inside a class (i.e. having complex inline functions) might mess up the resulting code and introduce debugging problems or weird behaviors during execution. And, finally, there's the "coding style" issue. So,
which approach is better?
Thank you :)
My style: I sometimes will put extremely short (one or two liner) functions in the class itself. Anything longer that I still want as an inlined function go as inline qualified implementations after the class definition, and oftentimes in a separate file that the header #includes at the end of the class definition.
The rationale for putting an inlined function outside the class is that the implementation of some function usually just gets in the way of a human reader's overall understanding of the class. A twenty line function can usually be summarized in a one line comment -- and that comment is all that is needed when you are reading the class definition. If you need more, go to the function definition, or better yet, Read The Fine Documentation. (Expecting someone to Read The F*** Code is a poor substitute for Fine Documentation.)
The best solution is to separate interface and implementation. Interface is your h-file. Put only prototypes there. Implementation goes to cpp-file. This approach has the following advantages:
Compilation goes faster because there is no need to compile function bodies several times.
Header dependency is simpler because there is no need to include all headers to h-file. Some of the headers are needed only in cpp-file and you can use forward declarations in h-file. Also you can avoid circular dependencies.
The last but not the least - it is easier for human beings to understand interface of your class. There is no code mess.
To answer the part of "Which approach is better?" - From C++ FAQ -
There are no simple answers: You have to play with it to see what is best. Do not settle for simplistic answers like, "Never use inline functions" or "Always use inline functions" or "Use inline functions if and only if the function is less than N lines of code." These one-size-fits-all rules may be easy to write down, but they will produce sub-optimal results.
Neither approach is better per se its a matter of preference and style. Personally I always think that defining the functions explicitly in a seperate .inline file is the best way. This way you are very explicit over what you do and you keep the header file clean.
Furthermore if you use a macro such as INLINE which is defined as follows:
#ifdef DEBUG
#define INLINE
#else
#define INLINE inline
#endif
You can then include the inline file from the header in release and from the CPP in debug. This means that even if the compiler inlines functions in debug you won't have any difficulties when debugging. Admittedly, though, this isn't such a problem for compilers these days so you may want to skip doing this unless using an old compiler.
Generally speaking, a member function which has only one or two statements is probably best with its body written in the class declaration—especially if there are many of them. A member function with more than 20-50 statements is probably best not in the class declaration. For lengths and complexities between, it depends on many factors.
For example, having the function body in a class module helps prevent unnecessary recompiling of dependent modules when the class declaration does not change—only a member function body. This can greatly increase productivity when developing the class. Once the class is stable, this becomes much less important.