I’m learning C++, and find no answer to the following:
I have a formula that calculates a result of two numbers from user input.
- How should the header file (“.h”) look, which contains this formula?
- How do I get the formula from the source code (“.cpp”)?
- How do I pass the result to the source code (“.cpp”)?
For you old-timers this is not a topic. Where can I find a good tutorial on C + +?
Greetings, Dino
The best tutorials can be found in books. There’s numerous topics on SO with good books recommendations.
In C++, free-standing functions should be either grouped in namespaces or as
staticclass members (but only if they are logically connected to a class).For your case, I’d go with the
namespace. Even so, there 3 possibilities, out of which 2 are prefferable:1) declare the function in a header and define it in a source file:
The preprocessor directives are include guards (you can google that). After this, you define it in a source file:
2) Both declare and define the function in the header as
inline(this will prevent multiple definitions of the functions). Usually done with relatively small functions that are called frequently, to prevent the call overhead and allow better optmizations:3) Declare and define the function in the header, marking it
static. This is not to be preffered, as it will create a copy of the function for each translation unit that includes the header.To use the function, you need only include the header where it is declared and call it.