C++ Progrramming
C++ Progrramming
RTQF LEVEL: 4
1
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
2
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
3
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
✓ Introduction to programming
definition
History
Here's a brief overview of the key milestones and individuals in the history of C++:
✓ Early Influences (1960s-1970s):
C++ finds its roots in the C programming language, which was developed at Bell Labs by
Dennis Ritchie in the early 1970s. C was a powerful and portable language known for its
efficiency and simplicity.
✓ Bjarne Stroustrup's Involvement (1979-1980):
Stroustrup's first C++ compiler, called "Cfront," was created in 1980. It translated C++ code
into C code, which could then be compiled using a C compiler.
✓ First Official Release (1985):
The first official release of C++, known as "C++ Release 1.0," was made available in 1985.
It introduced several key features, including classes, derived classes, and virtual functions,
laying the foundation for object-oriented programming in C++.
✓ Standardization Efforts (1989-1998):
In 1989, work began on standardizing the C++ language. The first official C++ standard,
known as "C++98" or "ISO/IEC 14882:1998," was published in 1998. This standardization
effort helped ensure the language's consistency and portability.
✓ Further Standardization (2011 and beyond):
4
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
C++ continued to evolve with new language features and libraries. The C++11 standard,
released in 2011, introduced significant enhancements, including lambda expressions, smart
pointers, and the Standard Template Library (STL) improvements.
Subsequent standards, such as C++14, C++17, and C++20, brought more features and
improvements, making C++ a more powerful and expressive language.
✓ Modern C++ (21st Century):
C++ has remained a popular language for various domains, including system programming,
game development, and high-performance applications.
The C++ community emphasizes modern C++ practices that promote safety, readability, and
maintainability through techniques like smart pointers, RAII (Resource Acquisition Is
Initialization), and more.
features are the core elements of the programming language specified by its standard, while
extensions are optional and non-standard additions that can extend the language's
functionality.
Extension/Feature Description
Permits the creation of multiple functions with the same name but different
Function Overloading parameter lists.
Standard Template Provides a collection of data structures and algorithms for common tasks,
Library (STL) including vectors, lists, maps, and algorithms like sorting and searching.
5
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Extension/Feature Description
Allows the handling of runtime errors and exceptions using try, catch, and
Exception Handling throw to ensure robust error recovery.
Dynamic Memory Supports dynamic memory allocation using new and deallocation using
Allocation delete, malloc, and free.
Applications
6
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
✓ Description of C++ Tools
2. Text editor
Text editors are lightweight software applications for writing and editing source code.
Examples: Visual Studio Code (VS Code), Sublime Text, Vim, Emacs.
3. compiler and Interpreter
Compilers and interpreters are essential tools for executing C++ code. Compilers translate
C++ source code into machine code or an intermediate code that can be executed, while
interpreters execute the code line by line.
Compiler Examples: GNU Compiler Collection (GCC), Clang, Microsoft Visual C++
Compiler
Interpreter Example:
C++ is primarily compiled, so it's not typically interpreted like languages such as Python or
JavaScript.
4. debugging
5. version control
Version control systems (VCS) help developers manage changes to their source code over
time, track revisions, collaborate with others, and revert to previous states if needed.
Examples: Git, Subversion (SVN), Mercurial.
7
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
✓ Tools installation
Code::Blocks:
Download and install Code::Blocks from the official website
(http://www.codeblocks.org/downloads).
Launch Code::Blocks after installation.
CLion (JetBrains):
Download and install CLion from the JetBrains website
(https://www.jetbrains.com/clion/download/).
8
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Launch CLion after installation and activate it if required.
Compiler installation
After installing GCC on Windows, you need to add its directory to the system's PATH
environment variable to make it accessible from the command prompt. Follow these steps:
9
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
5. In the "System Variables" section, scroll down and find "Path." Select it and click
"Edit."
6. Click "New" and add the path to the GCC bin directory (e.g., C:\MinGW\bin).
7. Click "OK" to close all the dialog boxes.
Verify setup
To verify that your IDE and compiler are correctly installed and configured, create a simple
C++ program and build/run it using the IDE.
For example, in Visual Studio Code:
1. Create a new C++ file (e.g., main.cpp).
2. Write a simple program in the file.
3. Save the file.
4. Press Ctrl+Shift+B to build and run the program.
10
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
The "Window" menu manages open documents and views within your IDE. It allows you to
switch between open files and arrange windows.
Help Menu:
The "Help" menu provides access to documentation, tutorials, and support resources for the
IDE. It often includes links to online documentation and community forums.
Icons and Toolbar:
The toolbar usually contains icons representing common actions like saving, building,
running, and debugging. Hovering over icons often displays tooltips with descriptions.
1. Header files
the header file instructs the C ++ compiler to include all the functions associated with that
title file. We have used just one header file, #include <iostream>, ‘iostream’ represents the
input-output stream.
The <iostream> header file allows you to use input and output functionality. Hence, helped
us to display the message “Hello World!” on the screen.
11
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
2. Namespace
A namespace is a descriptive region that provides scope to the identifiers (names of types,
functions, variables, etc.) within them. We use namespaces to organize code into sensible groups
and prevent possible word conflicts, especially when your codebase includes more than one library.
3. Comments
To give details and explanations about the code or blocks of code, we need to use comments.
Single-line comment is prefixed with two front slashes “//” and it ends when the user jumps to
another line.
//print statement
Multi-line comments begin with “/*” and end where “*/” is detected.
Sometimes, we need to add comments of more than one line, for that C++ supports another type of
comment.
The program must contain a main() method and the program execution will fail if there’s no main()
function. int main() is the main function where program execution begins and the return type is int.
But, we are not done yet, without return 0; the main() function won’t terminate and the execution
will fail.
5. Print statement
In C, we use printf() function along with format specifiers. Whereas in C++ we need not use format
specifiers. We just need to use the cout function along with ‘<<’, the output operator.
12
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
6. Tokens
A token is the smallest part of the program, which holds some meaning for the compiler. There are
5 types of token, they are:
✓ Keywords
✓ Identifiers
✓ Constants
✓ Strings
✓ Special Symbols
✓ Operators
13
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
VARIABLE
Variables in C++ is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable effects
that memory location.
In C++, all the variables must be declared before use.
How to Declare Variables?
A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;
e Demo
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Variable initialization
Variables are the names given by the user. A datatype is also used to declare and initialize a variable
which allocates memory to that variable. There are several datatypes like int, char, float etc. to
allocate the memory to that variable.
15
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
There are two ways to initialize the variable. One is static initialization in which the variable is
assigned a value in the program and another is dynamic initialization in which the variables is
assigned a value at the run time.
Global Variables
Global variables are defined outside of all the functions, usually on top of the program. The global
variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. Following is the example using global and local
variables −
OPERATOR
An operator is a symbol that operates on a value to perform specific mathematical or logical
computations. They form the foundation of any programming language. In C++, we have built-in
operators to provide the required functionality..
Operators in C++ can be classified into 6 types:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary or Conditional Operators
1) Arithmetic Operators
These operators are used to perform arithmetic or mathematical operations on the operands. For
example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used for multiplication, etc.
Arithmetic Operators can be classified into 2 Types:
A) Unary Operators: These operators operate or work with a single operand. For example:
Increment(++) and Decrement(–) Operators.
16
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
int a = 5;
Increment Increases the integer value of the variable by
++ a++; // returns
Operator one
6
Note: ++a and a++, both are increment operators, however, both are slightly different.
In ++a, the value of the variable is incremented first and then It is used in the program. In a++, the
value of the variable is assigned first and then It is incremented. Similarly happens for the decrement
operator.
B) Binary Operators: These operators operate or work with two operands. For example: Addition(+),
Subtraction(-), etc.
int a = 3, b = 6;
Addition + Adds two operands
int c = a+b; // c = 9
int a = 9, b = 6;
Subtraction – Subtracts second operand from the first
int c = a-b; // c = 3
int a = 3, b = 6;
Multiplication * Multiplies two operands
int c = a*b; // c = 18
Modulo int a = 8, b = 6;
% Returns the remainder an integer division
Operation int c = a%b; // c = 2
Note: The Modulo operator(%) operator should only be used with integers.
2) Relational Operators
17
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
These operators are used for the comparison of the values of two operands. For example, ‘>’ checks
if one operand is greater than the other operand or not, etc. The result returns a Boolean value,
i.e., true or false.
int a = 3, b =
6;
Is Equal To == Checks if both operands are equal a==b;
// returns
false
int a = 3, b =
6;
Checks if first operand is greater than the second
Greater Than > a>b;
operand
// returns
false
int a = 3, b =
6;
Greater Than or Checks if first operand is greater than or equal
>= a>=b;
Equal To to the second operand
// returns
false
int a = 3, b =
6;
Checks if first operand is lesser than the second
Less Than < a<b;
operand
// returns
true
int a = 3, b =
Less Than or Checks if first operand is lesser than or equal to
<= 6;
Equal To the second operand
a<=b;
18
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
// returns
true
int a = 3, b =
6;
Not Equal To != Checks if both operands are not equal a!=b;
// returns
true
3) Logical Operators
These operators are used to combine two or more conditions or constraints or to complement the
evaluation of the original condition in consideration. The result returns a Boolean value,
i.e., true or false.
int a = 3, b = 6;
Logical Returns true only if all the operands are true or non-
&& a&&b;
AND zero
// returns true
int a = 3, b = 6;
Returns true if either of the operands is true or non-
Logical OR || a||b;
zero
// returns true
int a = 3;
Logical
! Returns true if the operand is false or zero !a;
NOT
// returns false
4) Bitwise Operators
These operators are used to perform bit-level operations on the operands. The operators are first
converted to bit-level and then the calculation is performed on the operands. Mathematical operations
such as addition, subtraction, multiplication, etc. can be performed at the bit level for faster
processing.
19
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
int a = 2, b =
Copies a bit to the evaluated result if it exists in 3;
Binary AND &
both operands (a & b);
//returns 2
int a = 2, b =
Copies a bit to the evaluated result if it exists in 3;
Binary OR |
any of the operand (a | b);
//returns 3
int a = 2, b =
Copies the bit to the evaluated result if it is present 3;
Binary XOR ^
in either of the operands but not both (a ^ b);
//returns 1
int a = 2, b =
Shifts the value to left by the number of bits 3;
Left Shift <<
specified by the right operand. (a << 1);
//returns 4
int a = 2, b =
Shifts the value to right by the number of bits 3;
Right Shift >>
specified by the right operand. (a >> 1);
//returns 1
int b = 3;
One’s
~ Changes binary digits 1 to 0 and 0 to 1 (~b); //returns
Complement
-4
Note: Only char and int data types can be used with Bitwise Operators.
20
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
5) Assignment Operators
These operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value on
the right side must be of the same data type as the variable on the left side otherwise the compiler
will raise an error.
int a = 2, b
Add and First adds the current value of the variable on left
= 4;
Assignment += to the value on the right and then assigns the
a+=b; // a
Operator result to the variable on the left
=6
int a = 2, b
Subtract and First subtracts the value on the right from the
- = 4;
Assignment current value of the variable on left and then
= a-=b; // a =
Operator assign the result to the variable on the left
-2
int a = 2, b
Multiply and First multiplies the current value of the variable
= 4;
Assignment *= on left to the value on the right and then assign
a*=b; // a
Operator the result to the variable on the left
=8
int a = 4, b
Divide and First divides the current value of the variable on
= 2;
Assignment /= left by the value on the right and then assign the
a /=b; // a
Operator result to the variable on the left
=2
21
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
The ternary operator ? determines the answer on the basis of the evaluation of Expression1. If it
is true, then Expression2 gets evaluated and is used as the answer for the expression.
If Expression1 is false, then Expression3 gets evaluated and is used as the answer for the expression.
This operator takes three operands, therefore it is known as a Ternary Operator.
Example:
C++
int main()
{
int a = 3, b = 4;
// Conditional Operator
int result = (a < b) ? b : a;
cout << "The greatest number is " << result << endl;
return 0;
}
Output
The greatest number is 4
Time Complexity: O(1)
Auxiliary Space : O(1)
1 Control Structures
Control structures are portions of program code that contain statements within them and, depending
on the circumstances, execute these statements in a certain way. There are typically two kinds:
conditionals and loops.
22
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
1.1 Conditionals
In order for a program to change its behavior depending on the input, there must a way to test that
input. Conditionals allow the program to check the values of variables and to execute (or not
execute) certain statements. C++ has if and switch-case conditional structures.
1.1.1 Operators
Conditionals use two kinds of special operators: relational and logical. These are used to determine
whether some condition is true or false.
The relational operators are used to test a relation between two expressions:
Operator Meaning
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
They work the same as the arithmetic operators (e.g., a > b) but return a Boolean value of either true
or false, indicating whether the relation tested for holds. (An expression that returns this kind of
value is called a Boolean expression.) For example, if the variables x and y have been set to 6 and
2, respectively, then x > y returns true. Similarly, x < 5 returns false.
The logical operators are often used to combine relational expressions into more complicated
Boolean expressions:
Operator Meaning
&& and
|| or
! not
The operators return true or false, according to the rules of logic:
a b a && b
true true true
true false false
23
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
false true false
false false false
a b a || b
true true true
true false true
false true true
false false false
The ! operator is a unary operator, taking only one argument and negating its value:
a !a
true false
false true
Examples using logical operators (assume x = 6 and y = 2):
Of course, Boolean variables can be used directly in these expressions, since they hold true and
false values. In fact, any kind of value can be used in a Boolean expression due to a quirk C++ has:
false is represented by a value of 0 and anything that is not 0 is true. So, “Hello, world!” is true, 2 is
true, and any int variable holding a non-zero value is true. This means !x returns false and x && y
returns true!
if(condition)
{
statement1 statement2
…
}
24
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
The condition is some expression whose value is being tested. If the condition resolves to a value of
true, then the statements are executed before the program continues on. Otherwise, the statements
are ignored. If there is only one statement, the curly braces may be omitted, giving the form:
if(condition) statement
The if-else form is used to decide between two sequences of statements referred to as blocks:
if(condition)
{
statementA1 statementA2
…
} else
{
statementB1 statementB2
…
}
If the condition is met, the block corresponding to the if is executed. Otherwise, the block
corresponding to the else is executed. Because the condition is either satisfied or not, one of the
blocks in an if-else must execute. If there is only one statement for any of the blocks, the curly
braces for that block may be omitted:
if(condition) statementA1
else statementB1
The else if is used to decide between two or more blocks based on multiple conditions:
if(condition1)
{
statementA1 statementA2
…
}
else if(condition2)
{
statementB1 statementB2
…
25
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
}
If condition1 is met, the block corresponding to the if is executed. If not, then only if condition2 is
met is the block corresponding to the else if executed. There may be more than one else if, each
with its own condition. Once a block whose condition was met is executed, any else ifs after it are
ignored. Therefore, in an if-else-if structure, either one or no block is executed.
An else may be added to the end of an if-else-if. If none of the previous conditions are met, the else
block is executed. In this structure, one of the blocks must execute, as in a normal ifelse.
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int x = 6;
6 int y = 2;
7
8 if(x > y)
9 cout << “x is greater than y\n”;
10 else if(y > x)
11 cout << “y is greater than x\n”;
12 else
13 cout << “x and y are equal\n”;
14
15 return 0;
16 }
The output of this program is x is greater than y. If we replace lines 5 and 6 with
26
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
1.1.3 switch-case
The switch-case is another conditional structure that may or may not execute certain statements.
However, the switch-case has peculiar syntax and behavior:
switch(expression)
{
case constant1:
statementA1
statementA2
... break;
case constant2:
statementB1
statementB2 .
.. break;
... default:
statementZ1
statementZ2
...
}
The switch evaluates expression and, if expression is equal to constant1, then the statements
beneath case constant 1: are executed until a break is encountered. If expression is not equal to
constant1, then it is compared to constant2. If these are equal, then the statements beneath case
constant 2: are executed until a break is encountered. If not, then the same process repeats for each
of the constants, in turn. If none of the constants match, then the statements beneath default: are
executed.
Due to the peculiar behavior of switch-cases, curly braces are not necessary for cases where there is
more than one statement (but they are necessary to enclose the entire switch-case). switch-cases
generally have if-else equivalents but can often be a cleaner way of expressing the same behavior.
1 #include <iostream>
2 using namespace std;
3
27
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
4 int main() {
5 int x = 6;
6
7 switch(x) {
8 case 1:
9 cout << “x is 1\n”;
10 break;
11 case 2:
12 case 3:
13 cout << "x is 2 or 3";
14 break;
15 default:
16 cout << "x is not 1, 2, or 3";
17 }
18
19 return 0;
28
Prepared by Fidèle NDAYISHIMIYE
20 }
This program will print x is not 1, 2, or 3. If we replace line 5 with int x = 2; then the program will print x is
2 or 3.
1.2 Loops
Conditionals execute certain statements if certain conditions are met; loops execute certain statements while
certain conditions are met. C++ has three kinds of loops: while, do-while, and for.
while(condition)
{
statement1 statement2
…
}
As long as condition holds, the block of statements will be repeatedly executed. If there is only one
statement, the curly braces may be omitted. Here is an example:
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int x = 0;
6
7 while(x < 10)
8 x = x + 1;
9
10 cout << “x is “ << x << “\n”;
11
12 return 0; 13 }
29
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
The do-while loop is a variation that guarantees the block of statements will be executed at least once:
do
{
statement1 statement2
…
}
while(condition);
The block of statements is executed and then, if the condition holds, the program returns to the top of the
block. Curly braces are always required. Also note the semicolon after the while condition.
1.2.2 for
The for loop works like the while loop but with some change in syntax:
The for loop is designed to allow a counter variable that is initialized at the beginning of the loop and
incremented (or decremented) on each iteration of the loop. Curly braces may be omitted if there is only one
statement. Here is an example:
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 for(int x = 0; x < 10; x = x + 1)
7 cout << x << “\n”;
8
9 return 0;
10 }
This program will print out the values 0 through 9, each on its own line.
30
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
If the counter variable is already defined, there is no need to define a new one in the initialization portion of
the for loop. Therefore, it is valid to have the following:
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 int x = 0;
7 for(; x < 10; x = x + 1)
8 cout << x << “\n”;
9
10 return 0;
11 }
Note that the first semicolon inside the for loop's parentheses is still required.
A for loop can be expressed as a while loop and vice-versa. Recalling that a for loop has the form
initialization while(condition)
{
statement1 statement2
…
incrementation
}
1 #include <iostream>
2 using namespace std;
31
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
3
4 int main() {
5
6 for(int x = 0; x < 10; x = x + 1)
7 cout << x << “\n”;
8
9 return 0;
10 } is converted to
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 int x = 0;
7 while(x < 10) {
8 cout << x << “\n”;
9 x = x + 1;
10 }
11
12 return 0;
13 }
The incrementation step can technically be anywhere inside the statement block, but it is good practice to
place it as the last step, particularly if the previous statements use the current value of the counter variable.
It is possible to place ifs inside of ifs and loops inside of loops by simply placing these structures inside the
statement blocks. This allows for more complicated program behavior.
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int x = 6;
6 int y = 0;
32
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
7
8 if(x > y) {
9 cout << “x is greater than y\n”;
10 if(x == 6)
11 cout << “x is equal to 6\n”;
12 else
13 cout << “x is not equalt to 6\n”;
14 } else
15 cout << “x is not greater than y\n”;
16
17 return 0;
18 }
This program will print x is greater than y on one line and then x is equal to 6 on the next line.
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 for(int x = 0; x < 4; x = x + 1) {
6 for(int y = 0; y < 4; y = y + 1)
7 cout << y;
8 cout << “\n”;
9 }
10
11 return 0;
12 }
FUNCTION
A function is a group of statements that together perform a task. Every C++ program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division usually is such that each function performs a specific task.
33
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can call. For example,
function strcat() to concatenate two strings, function memcpy() to copy one memory location to another
location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.
Defining a Function
A C++ function definition consists of a function header and a function body. Here are all the parts of a
function −
⚫ Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this case,
the return_type is the keyword void.
⚫ Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
⚫ Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function may
contain no parameters.
⚫ Function Body − The function body contains a collection of statements that define what the function
does.
Example
Following is the source code for a function called max(). This function takes two parameters num1 and
num2 and return the biggest of both −
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
For the above defined function max(), following is the function declaration −
Parameter names are not important in function declaration only their type is required, so following is also
valid declaration −
Function declaration is required when you define a function in one source file and you call that function in
another file. In such case, you should declare the function at the top of the file calling the function.
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a function, you
will have to call or invoke that function.
35
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when it’s return statement is executed or when its function-ending closing brace
is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example −
Live Demo
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
return result;
}
I kept max() function along with main() function and compiled the source code. While running final
executable, it would produce the following result −
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into
the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function −
Call by Value
This method copies the actual value of an argument into the formal parameter of the function.
1
In this case, changes made to the parameter inside the function have no effect on the
argument.
Call by Pointer
This method copies the address of an argument into the formal parameter. Inside the function,
2
the address is used to access the actual argument used in the call. This means that changes
made to the parameter affect the argument.
Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the
3
function, the reference is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
37
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
By default, C++ uses call by value to pass arguments. In general, this means that code within a function
cannot alter the arguments used to call the function and above mentioned example while calling max()
function used the same method.
When you define a function, you can specify a default value for each of the last parameters. This value will
be used if the corresponding argument is left blank when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the function
definition. If a value for that parameter is not passed when the function is called, the default given value is
used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider
the following example −
Live Demo
#include <iostream>
using namespace std;
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;
return 0;
}
When the above code is compiled and executed, it produces the following result −
1. Built-in Functions:
2. User-Defined Functions:
3. Recursive Functions:
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
39
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
}
int main() {
// Declare and use a lambda function
auto add = [](int a, int b) -> int {
return a + b;
};
40
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
return 0;
}
5. Prototyping Function
Prototyping functions refer to the practice of declaring a function's signature or interface before providing its
full implementation.
Example:
1. # include < iostream >
2. using namespace std ;
3. // function prototype
4. void divide ( int , int ) ;
5. int main ( ) {
6. // calling the function before declaration.
7. divide ( 10 , 2 ) ;
8. return 0 ;
9. }
10. // defining function
11. void divide ( int a , int b ) {
12. cout < < ( a / b ) ;
13. }
C++ Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value.
To declare an array, define the variable type, specify the name of the array followed by square
brackets and specify the number of elements it should store:
string cars[4];
41
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
We have now declared a variable that holds an array of four strings. To insert values to it, we can use an
array literal - place the values in a comma-separated list, inside curly braces:
Array Initialization
You access an array element by referring to the index number inside square brackets [].
#include <iostream>
#include <string>
int main() {
return 0;
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
cars[0] = "Opel";
42
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
EXAMPLE
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
return 0;
}
❖ Iterating Over Array
You can loop through the array elements with the for loop.
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
return 0;
}
This example outputs the index of each element together with its value:
Example
43
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}
return 0;
}
44
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as follows:
array_name [size];
45
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
// 1d array declaration
int arr[5];
46
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Output
Elements of Array: 1 0 1 4 9
2. Multidimensional Array in C
Multi-dimensional Arrays in C++ are those arrays that have more than one dimension. Some of the
popular multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with more
dimensions than 3d arrays but they are avoided as they get very complex and occupy a large amount of
space.
A Two-Dimensional array or 2D array in C++ is an array that has exactly two dimensions. They can be
visualized in the form of rows and columns organized in a two-dimensional plane.
array_name[size1] [size2];
Here,
47
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
int main()
{
printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
Cout<<arr[i][j];
}
printf("\n");
}
48
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
return 0;
}
Output
2D Array:
10 20 30
40 50 60
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A 3D array
has exactly three dimensions. It can be visualized as a collection of 2D arrays stacked on top of each
other to create the third dimension.
49
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
int main()
{
// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };
// printing elements
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
50
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Cout<< arr[i][j][k];
}
Cout<<"\n";
}
Cout<<"\n \n";
}
return 0;
}
Output
10 20
30 40
50 60
00
51
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Procedural programming is about writing procedures or functions that perform operations on the data, while
object-oriented programming is about creating objects that contain both data and functions.
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
Class :Fruit
objects
When the individual objects are created, they inherit all the variables and functions from the class.
C++ Classes/Objects
Everything in C++ is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color, and methods,
such as drive and brake.
52
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Attributes and methods are basically variables and functions that belongs to the class. These are often
referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object constructor, or
a "blueprint" for creating objects.
Create a Class
Example
There are a few principle concepts that form the foundation of object-oriented programming −
Object
53
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
This is the basic unit of object oriented programming. That is both data and function that operate on data are
bundled as a unit called as object.
Class
When you define a class, you define a blueprint for an object. This doesn't actually define any data, but it
does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding their
background details, i.e., to represent the needed information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and maintained.
Similar way, C++ classes provides different methods to the outside world without giving internal detail
about those methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place. While working
with procedural languages, it is not always clear which functions work on which variables but object-
oriented programming provides you framework to place the data and the relevant functions together in the
same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name suggests
Inheritance is the process of forming a new class from an existing class that is from the existing class called
as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce the code
size.
Polymorphism
The ability to use an operator or function in different ways in other words giving different meaning or
functions to the operators or functions is called polymorphism. Poly refers to many. That is a single
function or an operator functioning in many ways different upon the usage is called polymorphism.
54
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Overloading
The concept of overloading is also a branch of polymorphism. When the exiting operator or function is
made to operate on new data type, it is said to be overloaded.
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should
extract out the codes that are common for the application, and place them at a single place and reuse them
instead of repeating it.
✓ Create an Object
In C++, an object is created from a class. We have already created the class named MyClass, so now we can
use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Class Methods
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and using the
dot syntax (.):
#include <iostream>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
56
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
}
To define a function outside the class definition, you have to declare it inside the class and then define it
outside of the class. This is done by specifying the name of the class, followed the scope resolution :: operator,
followed by the name of the function:
#include <iostream>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parameters
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj;
cout << myObj.speed(200);
return 0;
}
✓ Access Specifiers
Access specifiers define how the members (attributes and methods) of a class can be accessed.
In the following example, we demonstrate the differences between public and private members:
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
58
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
If you try to access a private member, an error occurs:
error: y is private
Constructors
A constructor in C++ is a special method that is automatically called when an object of a class is created.
To create a constructor, use the same name as the class, followed by parentheses ():
#include <iostream>
using namespace std;
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
✓ Constructors and Destructors
Constructors:
Constructors are special member functions in a class that are called when an object is created.
They initialize the object's data members and set up the object's state.
Constructors have the same name as the class and do not have a return type.
Example:
C++ code:
#include <iostream>
using namespace std;
class MyClass
{
public:
59
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
// Default Constructor
MyClass() {
// Initialization code
}
// Parameterized Constructor
MyClass(int value) {
// Initialization code with parameter
}
};
Destructors:
Destructors are special member functions that are called when an object goes out of scope or is explicitly
deleted.
They are used to clean up resources allocated by the object, such as dynamic memory or open files.
Destructors have the same name as the class preceded by a tilde (~) and do not take any parameters.
Example:
C++ code
#include <iostream>
using namespace std;
class MyClass
{
public:
// Constructor
MyClass() {
// Initialization code
}
// Destructor
~MyClass() {
// Cleanup code
}
};
60
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Copy Constructor:
A copy constructor is a special constructor that creates a new object by copying the values from an existing
object of the same class.
It is called when an object is passed by value or when an object is explicitly copied.
Example:
C++ code
#include <iostream>
using namespace std;
class MyClass
{
public:
// Copy Constructor
MyClass(const MyClass& other) {
// Copy values from 'other' to the new object
}
};
Deep Copy:
In the context of copy constructors, a deep copy involves creating a new object and copying not just the values
of the data members but also any dynamically allocated resources.
This ensures that the new object is independent and has its own copy of the data.
Shallow Copy:
Shallow copy, on the other hand, only copies the values of the data members without considering the content
they point to. If the object contains pointers to dynamically allocated memory, a shallow copy would copy
the memory addresses, not the actual data.
Destructor:
A destructor is responsible for cleaning up resources (memory, files, etc.) allocated during the object's
lifetime.
It is automatically called when the object goes out of scope or is explicitly deleted.
61
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
Example:
C++ code
#include <iostream>
using namespace std;
class MyClass
{
public:
// Destructor
~MyClass() {
// Cleanup code (e.g., release memory)
}
};
Constructor Overloading:
Constructor overloading refers to having multiple constructors in a class, each with a different set of
parameters.
This allows objects to be created in various ways, providing flexibility to the users of the class.
Example:
C++ code
#include <iostream>
using namespace std;
class MyClass
{
public:
// Default Constructor
MyClass() {
// Initialization code
}
// Parameterized Constructor
MyClass(int value) {
// Initialization code with parameter
}
62
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
✓ Constants:
Constants are values that do not change during the program's execution.
In C++, constants can be declared using the const keyword.
Constants are often used to improve code readability and maintainability.
Constant Member Variable:
A constant member variable is a variable within a class that is declared as constant using the const keyword.
Once initialized, its value cannot be changed.
Example:
C++ code
#include <iostream>
using namespace std;
class MyClass
{
63
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
public:
const int constantVar = 42; // Constant member variable
};
Constant Functions:
Constant functions are member functions declared with the const keyword.
They promise not to modify the state of the object on which they are called.
Constant functions can be called on constant and non-constant objects.
Example:
C++ code
#include <iostream>
using namespace std;
class MyClass
{
public:
void regularFunction() {
// Code that may modify object's state
}
64
Prepared by Fidèle NDAYISHIMIYE