- [Instructor] Creating your own functions
is a fundamental part of C plus plus programming.
It's also the basis of methods and classes.
So let's take a look
at how to create a function in C plus plus.
Here is func.cpp from chapter five of the exercise files,
and we have a very simple function here.
And all it does is it prints out a message
that says this is func.
A function is declared with a return type.
In this case, the return type is void.
Which means nothing is returned from this function.
Followed by the function name,
followed by a pair of parentheses.
The parenthesis may or may not include parameters.
The body of the function,
is a block of code in curly braces.
Notice that main is also a function,
as a return type which is int,
the name of the function, parentheses,
which sometimes does include parameters even from main
and a block of code in curly braces.
So when I build and run this,
you'll notice that main prints, this is main,
and then it calls func, which prints this as func.
So our results should be,
this is main, followed by this is func
and I'll build and run this,
and you'll see that's exactly what we get.
A function must be declared, before it is called.
If I move this function to after main,
now when I try to build, you notice I get an error
that says use of undeclared identifier func,
because func has not yet been declared before it's called.
So, what I can do is I can come up here
and I can declare it.
I can say void, func, and just put a semi-colon there.
And that's just a declaration with the actual definition
of the function later,
but this tells the compiler,
there's a function and it's called this,
and this is its function signature.
And so it's okay to call it and we can link it up later.
And so now I can build and run,
and it works exactly as expected.
It's common to put these declarations in a header file.
And so I can take this header file here
that says func.h, and I can copy it into my working project.
And then I can say up here, I can say, include func.h,
and now it'll build and run, just as if I had declared it
because inside of func.h,
is the function declaration, the forward declaration.
And this is actually very common to have a header file,
with your function declarations and other declarations
that are used in a program,
that doesn't necessarily have to clutter up the program.
So, that's a common way to do this.
Now, this is how you define and declare a function
and we'll get into many more details,
throughout this chapter.