Using functions in C++ - DVD Info
A good way to organize and structure computer programs is dividing them into smaller parts using functions. Each function carries out a specific task of the problem that we are solving.
You've seen that all programs written in C++ must contain the main
function where the program begins. You've probably already used functions such as pow
, sin
, cos
, or sqrt
from the cmath
library. Since in almost all of the upcoming lab experiences you will continue using pre-defined functions, you need to understand how to work with them. In future exercises, you will learn how to design and validate functions. In this laboratory experience, you will search and display information contained in a DVD data base to practice declaring simple functions and calling pre-defined functions.
Objectives:
- Identify the parts of a function: return type, name, list of parameters, and body.
- Call pre-defined functions by passing arguments by value ("pass by value"), and by reference ("pass by reference").
- Implement a simple function that utilizes parameters by reference.
Pre-Lab:
Before you get to the laboratory you should have:
Reviewed the following concepts:
a. the basic elements of a function definition in C++
b. how to call functions in C++
c. the difference between parameters that are passed by value and by reference
d. how to return the result of a function.
Studied the concepts and instructions for the laboratory session.
Taken the Pre-Lab quiz, available in Moodle.
Functions
In mathematics, a function is a rule that is used to assign to each element from a set called domain, one (and only one) element from a set called range. This rule is commonly represented with an equation, . The variable is the parameter of the function and the variable will contain the result of the function. A function can have more than one parameter, but only one result. For example, a function can have the form where there are two parameters, and for each pair that is used as an argument in the function, the function will only have one value of . The domain of the function tells us the type of value that the parameter should have and the range tells us the value that the returned result will have.
Functions in programming languages are similar. A function has a series of instructions that take the assigned values as parameters and performs a certain task. In C++ and other programming languages, functions return only one result, as it happens in mathematics. The only difference is that a programming function could possibly not return any value (in this case the function is declared as void
). If the function returns a value, we use the instruction return
. As in math, you need to specify the types of values that the function's parameters and result will have; this is done when declaring the function.
Function header
The first sentence of a function is called the header and its structure is as follows:
type name(type parameter01, ..., type parameter0n)
For example,
int example(int var1, float var2, char &var3)
would be the header of the function called example
, which returns an integer value. The function receives as arguments an integer value (and will store a copy in var1
), a value of type float
(and will store a copy in var2
) and the reference to a variable of type char
that will be stored in the reference variable var3
. Note that var3
has a & symbol before the name of the variable. This indicates that var3
will contain the reference to a character.
Calling a function
The following line assigns the value returned by the function example
to an integer variable x
:
x = example(2, 3.5, unCar);
Note that when calling the function we don't include the type of the variables in the arguments as in the function's definition. The third parameter &var3
is a reference variable. Thus, what is being sent to the third argument when calling the function is a reference to the variable unCar
. Any assignments that are made to the variable var3
will change the contents of the variable unCar
.
You can also use the function's result without having to store it in a variable.
The following line sends the return value of function example
to the cout
object, so that it is displayed in the terminal:
cout << "The result of the function example is:" << example(2, 3.5, unCar);`
or use it in an arithmetic expression:
y = 3 + example(2, 3.5, unCar);
Overloaded Functions
Overloaded functions are functions that have the same name, but different signatures. The signature of a function is composed of the name of the function and the types of parameters it receives. The signature does not include the return type.
The following function prototypes have the same signature:
int example(int, int) ;
void example(int, int) ;
string example(int, int) ;
Note that each has the same name, example
, and receives the same amount of parameters of the same type (int, int)
.
The following function prototypes have different signatures:
int example(int) ;
int elpmaxe(int) ;
Note that even though the functions have the same amount of parameters with the same type int
, the name of the functions is different.
The following function prototypes are overloaded versions of the function example
:
int example(int) ;
void example(char) ;
int example(int, int) ;
int example(char, int) ;
int example(int, char) ;
All of the above functions have the same name, example
, but different parameters. The first and second functions have the same amount of parameters, but their arguments are of different types. The fourth and fifth functions have arguments of type char
and int
, but they have a different order in each case.
In that last example, the function example
is overloaded since there are five functions with different signatures but with the same name.
Default Values
Values by default can be assigned to the parameters of the functions starting from the rightmost parameter. It is not necessary to initialize all of the parameters, but the ones that are initialized should be consecutive: parameters in between two parameters cannot be left uninitialized. This allows calling the function without having to send values in the positions that correspond to the initialized parameters.
Examples of Function Headers and Valid Function Calls:
Header:
int example(int var1, float var2, int var3 = 10)
Herevar3
is initialized to 10.Calls:
a.
example(5, 3.3f, 12)
This function call assigns the value 5 tovar1
, the value 3.3 tovar2
, and the value of 12 tovar3
.b.
example(5, 3.3f)
This function call sends the values for the first two parameters and the value for the last parameter will be the value assigned by default in the header. That is, the values in the variables in the function will be as follows:var1
will be 5,var2
will be 3.3, andvar3
will be 10.Header:
int example(int var1, float var2 = 5.0f, int var3 = 10)
Herevar2
is initialized to 5 andvar3
to 10.Calls:
a.
example(5, 3.3f, 12)
This function call assigns the value 5 tovar1
, the value 3.3 tovar2
, and the value 12 tovar3
.b.
example(5, 3.3f)
In this function call only the first two parameters are given values, and the value for the last parameter is the value by default. That is, the value forvar1
within the function will be 5, that ofvar2
will be 3.3, andvar3
will be 10.c.
example(5)
In this function call only the first parameter is given a value, and the last two parameters will be assigned values by default. That is,var1
will be 5,var2
will be 5.0, andvar3
will be 10.
Example of a Valid Function Header with Invalid Function Calls:
Header:
int example(int var1, float var2 = 5.0f, int var3 = 10)
Invocation:
a.
example(5, , 10)
This function call is invalid because it leaves an empty space in the middle argument.b.
example()
This function call is invalid becausevar1
was not assigned as a default value. A valid call to the functionexample
needs at least one argument (the first).
Examples of Invalid Function Headers:
int example(int var1 = 1, float var2, int var3)
This header is invalid because the default values can only be assigned starting from the rightmost parameter.int example(int var1 = 1, float var2, int var3 = 10)
This header is invalid because you can't place parameters without values between other parameters with default values. In this case,var2
doesn't have a default value butvar1
andvar3
do.
DVD Movies and the DVD Data Base
DVD stands for "digital versatile disk" or "digital video disk", which is an optical disc format for storing digital information invented by Philips, Sony, Toshiba, and Panasonic in 1995. The DVD offers larger storage capacity than compact disks (CD) but has the same dimensions. DVDs can be used to store any kind of digital data but they are mainly famous for their use in the distribution of movies.
example
functions would be called by the following instruction: example(42, 'a')
?
int example(int) ;
int example(int, int) ;
int example(char, int) ;
int example(int, char) ;
None of the above
int example(int, char);
.
int foo01(int a, int b, int c = 5)
. Would the following be a valid invocation?
cout << foo01(1, 2) << endl;
foo01
can be invoked with either the first two argumensts or all three arguments since the last argument has a default value.
arg01
after line 19 is executed?
void
command erases the valueejercicio
. Its final value is 4.
ejercicio
is of type "void", thus the variable will have no valueejercicio
var02 is assigned a value of 2. Therefore, the value of arg02 after the function call in line 19 is 2.
Laboratory Session:
In this laboratory session we will be using a database of DVD movies maintained by http://www.hometheaterinfo.com/dvdlist.htm. This database contains 44MB of information for movies that have been distributed in DVD. Some of the stored information in the database for each DVD is: DVD title, publishing studio, date of publication, type of sound, versions, price, rating, year and genre. The information for each movie is stored in the following format:
DVD_Title|Studio|Released|Status|Sound|Versions|Price|Rating|Year|Genre|Aspect|UPC|DVD_ReleaseDate|ID|Timestamp
For example,
Airplane! (Paramount/ Blu-ray/ Checkpoint)|Paramount||Discontinued|5.1 DTS-HD|
LBX, 16:9, BLU-RAY|21.99|PG|1980|Comedy|1.85:1|097361423524|2012-09-11 00:00:00|
230375|2013-01-01 00:00:00
Exercise 1 - Familiarize Yourself with the Defined Functions
The first step in this laboratory experience is to familiarize yourself with the functions that are already defined in the code. Your tasks require that you imitate what the functions do, for this reason it is important that you understand how to call, declare and define the functions.
Instructions
Load the project
DVDInfo
intoQtCreateor
. There are two ways to do this:- Using the virtual machine: Double click the file
DVDInfo.pro
located in the folderhome/eip/labs/functions-dvdinfo
of your virtual machine. - Downloading the project's folder from
Bitbucket
: Use a terminal and write the commandgit clone http://bitbucket.org/eip-uprrp/functions-dvdinfo
to download the folderfunctions-dvdinfo
fromBitbucket
. Double click the fileDVDInfo.pro
located in the folder that you downloaded to your computer.
- Using the virtual machine: Double click the file
Configure the project. The file
main.cpp
has the function calls that you will use in the next exercises. The declarations and definitions of the functions that will be called can be found in the filesmovie.h
andmovie.cpp
.Double click on the file
movie.h
that contains this project's function prototypes. Go tomovie.h
and identify which functions are overloaded and describe why.Study the function prototypes and documentation in
movie.h
so that you understand the task they carry out and the data types they receive and return. For each of the following functions, identify the data types they receive and return:showMovie showMovies getMovieName getMovieByName
You can find the function definitions in the file
movie.cpp
. Note that some versions of the functionshowMovie
use the object calledfields
of theQStringList
class. The purpose of this object is to provide easy access to information fields of each movie, using an index between 0 and 14. For example, you may use fields[0] to access a movie’s title, fields[1] to access a movie’s studio, fields[8] to access its year, and so forth.
movie.h
?
showMovies
is overloaded. There are two versions of showMovies
.
Exercise 2 - Call and Modify Functions
In this exercise you will modify the main
function and some of the pre-defined functions so that they display only certain movies from the database, display only part of the information, or display the information in a specific format.
Instructions
Notice the following line in the main funcion.
filemanip file("dvd_csv.txt") ;
Its purpose is to associate the object called
file
with the data filedvd_csv.txt
. When openning a data file in a program it is often necessary to specify the file's absolute path to guarantee that the program finds the file regardless of where it is executed.Find out the absolute path of
dvd_csv.txt
and substitute it for the current"dvd_csv.txt"
string. For example, after the change the line might look as follows:filemanip file("/home/eip/functions-dvdinfo/dvd_csv.txt") ;
Compile and run the program. If you see errors such as
Cannot open dvd_csv.txt
, then the path is incorrect. Correct the path until you get no errors when executing.Perform the following implementations in the
main
function (in themain.cpp
file):- Add code so that the program displays the movies that have positions from 80 to 100.
- Add code so that the program displays only the movies that have “forrest gump” in the title.
- Add code so that the program displays only the movie in position 75125 using function composition and the function
showMovie
. - Add code so that the program displays the name and the rating of the movie in position 75125.
Modify the
getMovieInfo
function in the filemovie.cpp
so that it receives an additional parameter by reference where the name of the movie will be assigned. Remember that you must also modify the function's prototype inmovie.h
.- Add the necessary code to the
main
function so that, usinggetMovieInfo
, it displays the name, rating, year and the genre of the movie in position 75125 in one line. Hint: note that the functiongetMovieInfo
has parameters that are passed by reference.
Exercise 3 - Define and Implement Functions
The functions whose prototypes are in movie.h
are implemented in the file movie.cpp
. In this exercise you will use the files movie.h
, movie.cpp
, and main.cpp
to define and implement additional functions. As you implement these functions, remember to use good programming techniques and document your program.
Instructions
Study the functions that are already implemented in
movie.cpp
so that they may be used as examples for the functions you will create.Implement a function
getMovieStudio
that receives a string with the information of a movie and returns the name of the film's studio. Remember to add the function's prototype in the filemovie.h
. Invoke the functiongetMovieStudio
inmain()
to display the name and studio of the movie in the position 75125 and demonstrate its functionality.Implement an overloaded function
getMovieInfo
that returns the name of the studio as well as the name, rating, year and genre. Call the functiongetMovieInfo
inmain()
to display the name, studio, rating, year and genre of the movie in the position 75125 and demonstrate its functionality.Implement a function
showMovieInLine
that displays the information displayed byshowMovie
, but in a single line. The function should have a parameter to receive a string of information of the movie. Call the functionshowMovieInLine
inmain()
to display the information for the movie in position 75125 to demonstrate its functionality.Implement a function
showMoviesInLine
that displays the same information displayed byshowMovies
(all of the movies within a range of positions) but in a single line per movie. For example, a function call would be:showMoviesInLine(file, 148995, 149000);
. Call the functionshowMoviesInLine
inmain()
to display the information and demonstrate its functionality.
Deliverables
Use "Deliverables" in Moodle to hand in the files main.cpp
, movie.cpp
, and movie.h
with the function calls, changes, implementations and declarations that you made in Exercises 2 and 3. Remember to use good programming techniques, include the names of the programmers involved, and document your program.
References
[1] http://mathbits.com/MathBits/CompSci/functions/UserDef.htm
[2] http://www.digimad.es/autoria-bluray-dvd-duplicado-cd-video.html