CS240 Classes cont Dick Steflik Member functions Member
CS-240 Classes (cont) Dick Steflik
Member functions • Member functions of a class include – getters • used to retrieve state data – setters • used to set state data – mutators • used to modify state data – functions that model the classes behavior • tend to be action words (verbs or verb phrases) – take_off , reverse_direction, open. . .
Function prototypes • Prototype are models of how a function is to be called – are not necessarily part of the function definition, but may be • float calculate_attack_angle (float, float); – notice that in a prototype only the types are required, parameter names are not
Function signatures • The signature of a function consists of: – returned type (if any) – the function name – the ordered set of types in the parameter list • within its scope, a function’s signature must be unique even if its name is overloaded
Parameters • Parameters are required on a function definition – parameter consists of a type and an identifier • function formal parameters – parameters in the function definition • alias names for the actual arguments ex. boolean exists(const point p); • scope is local to the function • parameters may be passed to a function – by value – by reference
Value Parameters • “read only” or “input only” parameters • makes a local copy (on the stack) of the value for use in the function; copies value of argument before running the function • “pass by value” • slower than pass by reference • use only for small objects
Reference Parameters • “read/write” parameter; value of argument can be changed • uses address of argument to manipulate it • doesn’t require local storage • use & to identify reference parameters – remember & is the address operator ex. void rotate (point & p);
Reference Parameters (cont. ) • use const reference parameters instead of value parameters (faster), less memory rqd. • const indicates a promise to not modify the reference parameter exists ex. double distance(const point & p); p is passed by reference as an input only parameter
Inlining functions • Two ways: – inline keyword (place on function definition line) – replaces a call to the function with a copy of the function’s code. – defining the function in the class definition automatically makes it inline – use for small functions • many calls to the function will bloat the program • slightly faster than a regular function call
Function Overloading • The function name may be reused (overloaded) within a class • each definition must have a unique signature (pattern made up of function name and the parameter types)
- Slides: 10