Function (C++)
From StudyWiki
Contents |
Overview
- C++ provides functions as well as object orientated programming
- entities may exist outside of any object
- it is possible to define functions outside of any class
- a function is called by name
- e.g. functionx();
- each function consists of a function prototype and function definition
Function Declaration
<return type> <function name> ( <parameter list> );
where
- <return type> is a data type
- <function name> is the name of the function
- <parameter list> is a comma separated list of parameters in the format:
- <data type> <parameter name>
There is no function body, and the prototype ends with a semi-colon, no brace block
Default Parameters
- default values for parameters can be specified in the function declaration
int printChar(string pString, int position==1);
Function Overloading
- signature
- the function declaration without the return type
Function Definition
<return type> <function name> ( <parameter list> ){
<function body>
}
where
- <return type> is a data type
- <function name> is the name of the function
- <parameter list> is a comma separated list of parameters in the format:
- <data type> <parameter name>
- <function body> is the statements that perform the function and return the correct data type.
Invoking Functions in Other Files
- this is valid so long as the declaration is visible
- we can define functions using 2 files
- a .hpp file
- a header file containing the function declaration
- a .cpp file
- contains the function definition
- a .hpp file
- any file can use a function by including the the header file
Parameter Passing
Call-By-Value
- C++ uses call-by-value by default
Call-By-Reference
- it is illegal to pass a constant to a reference parameter
- actual arguments must be type compatible with formal parameters without typecast
Call-By-Constant Reference
- guarantees the argument is not changed when passed by call-by-reference
- used when call-by-value is not suitable due to large objects
- call-by-constant reference is more efficient
- use both const and & modifiers
Main Function
2 formats:
no parameters
int main ()
{ return 0; }
int main (int argc, char *argv[]){
cout << "Run program" << argv[0] << endl;
return 0;
}
- argc
- the total number of arguments from the command line, including the program name
- argv[]
- an array of pointers to characters, which stores the arguments as strings
