Functions are written in the global scope. That means that they can be accessed by any other function (including themselves) in this cpp file as long as they are declared or defined before the other functions.
1 2 3 4 5 6 7 8 9
|
void func2(); // Declaration of func2
void func1(){
cout << 1;
}
void func2(){ // Definition of func2
cout << 2;
}
|
Function 1 can access function 2 because function 2 is declared above function 1. Function 2 can access function 1 because function 1 is defined above function 2.
1 2 3 4 5 6 7
|
void func1() {
cout << 1;
}
void func2() {
cout << 2;
}
|
In this case, function 2 can access function 1, but function 1 cannot access function 2 because there is no forward declaration.
To expand the scope of a function so that it is available to other cpp files, you would put the declaration in a header.
To limit the scope of a function, you could put the definition and declaration in a
namespace
or
class
(depending on how you are writing things). In the case of a
namespace
, others would still be able to access that function, but they'd have to manually specify your namespace first. In the case of a
class
, only other functions in that class would be able to access a
private
function.