Functions and Objects

Functions in C++

A function is a block of code that can be called from another location in the program or class. It is used to reduce the repetition of multiple lines of code. The return statement concludes the execution of the block of code. The function can either return a value (of dataType, declared in the function header), or return nothing (use the 'void' dataType).

Within classes, functions are known are 'Methods'.


Syntax
dataType functionName (methodParameters) {  //function header
    //statements that execute when called
}
 
//function call within the class:
functionName(passedParameters); 
 
//method call outside of the class, access using an object instance
classInstance.functionName(passedParameters);

Notes

functionName is defined by the programmer, and dataType is the data type of the result from calling the function.

functionParameters contain data used within the method, stored using variables. Parameters are defined as: (dataType parameterName), which is the data type of the input parameter and the name of the parameter as seen within the function. There can be multiple parameters separated by a comma.

The function can only access other global functions and variables, ones passed into the function, as well as ones within the same class.

Often times, the 'const' keyword is used with function declaration and/or the parameters. This indicates that either contents of the class or parameters will not be modified within the function.


Example
class Numbers {
public:
    int max = findMaximum(3,5) //call within the class, will return 5
    Numbers() {}
    int findMaximum(int number1, int number2) { 
        //3 stored in number1, 5 stored in number2
        int maximum = number2; 
        if (number1 > number2) maximum = number1; 
        return maximum; 
    }
}
 
//within the class
Numbers numberClass = new Numbers();
int maximum = numberClass.findMaximum(3, 5);

See Also
Documentation

Functions - C++ Tutorials

Add to Slack

< Instantiation   |   Operator Overloading >

© 2019 SyntaxDB. All Rights Reserved.