Содержание:
Theory
Standard functions
The math functions are declared in the <cmath>
header file:
#include <cmath> abs(x); floor(x); sin(x); pow(x, y); sqrt(x); |
User functions
sample 1:
//... int abs(int x) { return x > 0 ? x : -x; // exit the function } int main() { cout << abs(-35); // 35 system("pause"); return 0; } |
The abs
function returns integer value and have got single integer x
parameter.
sample 2:
//... void print(int i) { cout << "value = " << i; } int main() { print(40); system("pause"); return 0; } |
The print
function returns no value and have got single integer i
parameter. We can call it procedure (because it doesn’t return value).
Encapsulation
In C++, data and functionality are separated into two separate protections: public and private.
The protection level determines the access that “client code” has to the member data or functionality:
- Public members can be accessed by client code.
- Private members cannot be accessed by client code (only used within the functions themselves).
In C++, the interface (.h
file) to the function is defined separately from the implementation (.cpp
file).
Multi-file layout
To make an application, you usually need to create 3 files: header file (.h
), implementation file (.cpp
), and main file (.cpp
).
- A header file (
.h
) defines the interface to functions, that is declaration(s) of the function(s) - Implementation
.cpp
file contains all of the logic of the functions or methods. Header.h
file must be included here. - Main
.cpp
file contains of the main function, the starting point of all C++ programs, and here header.h
file also need to be included.
Let’s look at the example of 3 files of single application.
Sample header file (tasks.h):
#ifndef TASKS_H #define TASKS_H //calculates a triangle perimeter double perimeter(double, double, double); #endif TASKS_H |
Sample implementation file (.cpp):
#include "tasks.h" //calculates a triangle perimeter double perimeter(double a, double b, double c) { //TODO } |
Sample main file (.cpp):
#include <iostream> #include "tasks.h" using namespace std; void main() { //prompt user to enter data //call the function //print out the result system("pause"); } |
.cpp
files make requests to include various header files.cpp
file with all of its extra included content will be compiled into object file. (a file has a .o
extension, that is an object file.) Each cpp file is separately compiled into an object file.Labs and Tasks
To do: Create an application to find the volume and surface area of a cube. The length of the cube side is given (it is entered).
Note: Three solutions must be presented: 1) Without using functions and multi-file application, 2) Using functions, 3) Creating a multi-file application.
Expected output:
Please enter the cube side length: 3.48 Volume: 42.1442 Surface area: 72.6624
[Solution and Project name: Lesson_2Lab1
, files’ names HeaderL2Lab1.h
, ImpL2Lab1.cpp
, MainL2Lab1.cpp
]
✍ How to do:
- Open Microsoft Visual Studio. Select menu item File -> New project. In the Template region find C++ and then, Win32 Console Application.
- Create a new console project, name your project Lesson_2Lab1. Among the Additional options mark Empty project and nothing more must be marked. Click Finish button.
- In the Solution Explorer window find a Source files folder, click the right mouse button on it and select Add -> New Item. We’re going to create two
.cpp
files. Call themImpL2Lab1.cpp
– implementation file andMainL2Lab1.cpp
– file with a main function. - Now, find a Header files folder, click the right mouse button on it and select Add -> New Item. We’re going to create
.h
file, and give it a nameHeaderL2Lab1.h
. - First, we’re going to make this task without functions and encapsulation. So, we should set the cube side length value, and calculate the cube volume and surface area.
- Declare a variable of type double for
length
and set a value for it. Don’t forget to includeiostream
header, since we’re going to read/write to the console: - To prevent console window from closing, you should use pause. The main function must return 0:
- Declare variables for the cube volume and surface area. Calculate the values for them:
- After, you can print out the result to the console:
- Run the application and check the output.
- We’re going to modify our application creating methods to calculate the values of volume and surface area.
- Find the lines with the variables declarations and calculations and comment them out:
- Let’s create a method named
getVolume
to calculate a cube volume. It must return double type, since the cube side length is also of double type. Before the method signature you should define the method. You must add the code before the main function: - Place the declaration of the length inside the main function:
- Create a method named
getSurfaceArea
to calculate a cube surface area. It must be of double type too. Place the code before the main function: - The compiler doesn’t run functions until we call them. Therefore, you must call your methods. Now you can use the variables to store the function returning results. Place the code inside the main function:
- Run the application and check the output. The results must be as they were.
- We’re going to modify our application creating a multi-file one.
- In the Solution Explorer window select (mouse double click) the header file you created (
HeaderL2Lab1.h
). Inside the code editor window, you must add your method declarations only (you can cut them from your main file and paste here): - In the Solution Explorer window select (mouse double click) the implementation file you created (
ImpL2Lab1.cpp
). Inside the code editor window, you must add your method functionalities (cut them from the main file and paste here). And don’t forget to include the header file first: - Now, we can go ahead and clear up the parts of a code we don’t need anymore within the main function. So, this is what you have in your
MainL2Lab1.cpp
: - Run the application and check the output. The results must be as they were.
- Three files must be uploaded to the moodle system:
HeaderL2Lab1.h
,ImpL2Lab1.cpp
,MainL2Lab1.cpp
.
1) Without using functions and multi-file application:
#include <iostream> int main() { double length; std::cout << "please enter the cube side length: "; std::cin >> length; // … }
//… system("pause"); return 0; }
double volume = length * length * length; double surfaceArea = 6 * length * length;
std::cout << "Volume: " << volume << std::endl; std::cout << "Surface area: " << surfaceArea << std::endl;
2) Using functions:
//double volume = length * length * length;
//double surfaceArea = 6 * length * length;
double getVolume(double length); double getVolume(double length) { return length * length * length; } int main() { //…
int main() { double length;
double getSurfaceArea(double length); double getSurfaceArea(double length) { return 6 * length * length; }
double volume = getVolume(length); double surfaceArea = getSurfaceArea(length);
3) Creating a multi-file application
#pragma once // calculates a cube volume double getVolume(double length); // calculates a cube surface area double getSurfaceArea(double length);
getVolume
works, how getSurfaceArea
works. All we’ve done is declare that these are the functionalities of our program. We need to look at our .cpp
file to find out how they actually work.— This
pragma once
line instructs the compiler to only compile this code once. Even if multiple people use our class, we’ll only want the definition of our methods to be defined exactly once.— Note that you should always place the comments before each function.
#include "HeaderL2Lab1.h" double getVolume(double length) { return length * length * length; } double getSurfaceArea(double length) { return 6 * length * length; }
— We have a pound (
#
) include that includes a reference to our header.— We have the implementation of our two functions that were defined in our
.h
file.
#include <iostream> #include " HeaderL2Lab1.h" int main(){ double length; std::cout << "please enter the cube side length: "; std::cin >> length; //double volume = length * length * length; //double surfaceArea = 6 * length * length; double volume = getVolume(length); double surfaceArea = getSurfaceArea(length); std::cout << "Volume: " << volume << std::endl; std::cout << "Surface area: " << surfaceArea << std::endl; system("pause"); return 0; }
Notes on all tasks
Lesson_2Lab1 folder
.[Solution and Project name: Lesson_2Lab1
, files’ names tasks.h
, tasks.cpp
, main.cpp
]