- Code can be organized into functions
- Functions create a scope {}
- Single return value from a function
- Any number of input variables of any type
- Should do only one thing and do it right
- Name must show what the function does
- Is small enought to see all the code at once
- Name clearly states what the function does
Function declaration sets up an interface.
void FuncName(int param);
- Move all declarations to header files (*.h)
Function definition holds the implementation of the function that can even be hidden from the user.
void FuncName(int param) {
// Implementation details.
cout << "This function is called FuncName! ";
cout << "Did you expect anything useful from it?";
}
- Implementation goes to *.cpp or *.cc
Functions can accept default arguments. Only set in declaration not in definition.
Passing big objects
By default in C++, objects are copied when passed into functions. If objects are big it might be slow. Pass by reference to avoid copy.
void DoSmth(std::string huge_string ); // Slow. Copy
void DoSmth(std::string& huge_string ); // Faster. Pass by reference
Pass const reference to the function. Passed object stays intact.
void DoSmth(const std::string& huge_string );
Avoid using non-const reference.