0% found this document useful (0 votes)
65 views64 pages

C++ Progrramming

Uploaded by

kezaidriteninel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views64 pages

C++ Progrramming

Uploaded by

kezaidriteninel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

IMBANGUKANABIGWI

Kigali-Rwanda TOP PRACTICAL SKILLS

SECTOR: ICT & MULTIMEDIA

SUB-SECTOR/TRADE: COMPUTER SYSTEM AND ARCHITECTURE

RTQF LEVEL: 4

ACADEMIC YEAR: 2023 -2024

CERTIFICATE TITLE: TVET CERTIFICATE IV IN COMPUTER SYSTEM AND


ARCHITECTURE
Module Name: Fundamental of c++
Module Code: GENCF401
Credits:7
Hours:70

1
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++

Elements of Competence and Performance Criteria

2
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++

3
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++

Learning outcome 1: Apply basic C++ Concepts

1. Preparation of Development Environment

✓ Introduction to programming

definition

Programming is the process of designing and instructing a computer to perform specific


tasks or solve problems. It involves creating a set of instructions (code) in a programming
language that a computer can understand and execute.

C++: C++ is a general-purpose, high-level programming language that extends the C


programming language with features like object-oriented programming, classes, and
templates.

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 and extension of C++

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

Allows the creation of user-defined classes and objects for encapsulation


Classes and Objects and data abstraction.

Inheritance is a feature of object-oriented programming where a class


(subclass or derived class) can inherit properties and methods from another
Inheritance class (superclass or base class).

means having many forms. Typically, polymorphism occurs when there is a


Polymorphism hierarchy of classes and they are related by inheritance.

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.

Offers RAII-based management of dynamic memory allocation through


Smart Pointers shared_ptr, unique_ptr, and weak_ptr to prevent memory leaks.

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.

Offers a comprehensive library of functions and classes for input/output,


Standard Library string manipulation, and other common tasks.

Dynamic Memory Supports dynamic memory allocation using new and deallocation using
Allocation delete, malloc, and free.

Allows the creation of anonymous functions for concise, in-place function


Lambda Expressions definitions.

Enhances performance by efficiently transferring resources from one object


Move Semantics to another, reducing unnecessary copying.

Provides features for concurrent programming using std::thread,


Multithreading std::mutex, and other constructs in the Standard Library.

Applications

C++ is used in a wide variety of applications, including:

1. System Software: C++ is commonly used to develop operating systems, device


drivers, and other system-level software.
2. Game Development: Many video games are developed using C++ due to its
performance and capabilities.
3. Application Software: C++ is used to create desktop applications, including office
suites, media players, and graphics software.
4. Embedded Systems: C++ is suitable for programming embedded systems, such as
microcontrollers in IoT devices and automotive systems.
5. Web Development: While not as common as languages like JavaScript and Python
for web development, C++ can be used for server-side scripting and certain web
applications.
6. Scientific and High-Performance Computing: C++ is chosen for its efficiency in
scientific simulations, numerical analysis, and parallel computing.
7. Financial Software: Many financial applications, including trading platforms and
risk management systems, are written in C++ due to its performance and precision.

6
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
✓ Description of C++ Tools

1. IDE (Integrated Development Environments)

Description: IDEs are comprehensive software applications that provide an integrated


environment for C++ development.
Examples: Visual Studio (Visual C++), Eclipse CDT, CLion, Code::Blocks.

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

Debugging tools help developers identify and fix issues.


Examples: GDB (GNU Debugger), Visual Studio Debugger, LLDB.

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

Setting up your development environment for C++ involves installing an Integrated


Development Environment (IDE), a C++ compiler, and configuring environment variables.
Here are the general steps to install and set up these tools:
IDE installation

Visual Studio Code (VS Code):


Download and install Visual Studio Code from the official website
(https://code.visualstudio.com/).
Launch VS Code after installation.
Open the Extensions sidebar (Ctrl+Shift+X) and search for the "C/C++" extension by
Microsoft. Click "Install."

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

GCC (GNU Compiler Collection):


✓ On Linux:
Most Linux distributions come with GCC preinstalled. You can check by running g++ --
version in the terminal.
If not installed, you can install GCC through your package manager. For example, on Ubuntu,
you can use sudo apt-get install g++.
✓ On Windows:
You can install GCC via MinGW (Minimalist GNU for Windows).
Download and run the MinGW installer from the official website (http://www.mingw.org/).
During installation, select the "g++" package for installation.
Microsoft Visual C++ Compiler (for Windows):
If you are using Visual Studio, the Visual C++ compiler is included. You can install Visual
Studio from the official website (https://visualstudio.microsoft.com/).

setup environment variable path

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:

1. Find the directory where GCC is installed (e.g., C:\MinGW\bin).


2. Right-click on "This PC" or "My Computer" and select "Properties."
3. Click on "Advanced system settings."
4. In the "System Properties" window, click the "Environment Variables" button.

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.

✓ Test Development environment

Description of IDE menus and Icons

general overview of common menus and icons you might encounter:


File Menu:
This menu typically includes options for creating new files/projects, opening existing files,
saving, and exiting the IDE.
Edit Menu:
The "Edit" menu contains options for editing your code, such as copying, cutting, pasting,
and undo/redo operations.
View Menu:
The "View" menu allows you to customize the layout and appearance of your IDE. It often
includes options for toggling toolbars, panels, and views.
Build/Compile Menu:
The "Build" or "Compile" menu includes options to build and compile your code into an
executable. It may also contain options to clean the project or rebuild it.
Run/Debug Menu:
The "Run" or "Debug" menu is used for executing and debugging your code. You can run
your program, set breakpoints, and step through code using this menu.
Window Menu:

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.

Description of C++ syntax

Let discuss every component to clear our understanding:

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.

a. Single-line comments (//)

Single-line comment is prefixed with two front slashes “//” and it ends when the user jumps to
another line.

//print statement

b. Multi-line comments (/* This is the hello world program */)

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.

4. The main method

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.

cout <<“Hello World, welcome to TechVidvan”<<endl;

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;

// Declaring multiple variables:


type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore
‘_’ character. However, the name must not start with a number.
Initialization of a variable in C++
Examples:
// Declaring float variable
float simpleInterest;

// Declaring integer variable


int time, speed;

// Declaring character variable


char var;
We can also provide values while declaring the variables as given below:
int a=50,b=100; //declaring 2 variable of integer type
float f=50.8; //declaring 1 variable of float type
char c='Z'; //declaring 1 variable of char type
Rules For Declaring Variable
⚫ The name of the variable contains letters, digits, and underscores.
⚫ The name of the variable is case sensitive (ex Arr and arr both are different variables).
⚫ The name of the variable does not contain any white space and special characters (ex #,$,%,*,
etc).
14
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
⚫ All the variable names must begin with a letter of the alphabet or an underscore(_).
⚫ We cannot used C++ keyword(ex float,double,class)as a variable name.
SCOPE OF VARIABLE
A scope is a region of the program and broadly speaking there are three places, where variables can
be declared −
local variables variable declared Inside a function or a block.
Global variables variable declared Outside of all functions
Local Variables
Variables that are declared inside a function or block are local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions
outside their own. Following is the example using local variables −
Liv

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.

The following is the syntax of variable initialization.

datatype variable_name = value;

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++

Name Symbol Description Example

int a = 5;
Increment Increases the integer value of the variable by
++ a++; // returns
Operator one
6

Decrement Decreases the integer value of the variable by int a = 5;



Operator one a–; // returns 4

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.

Name Symbol Description Example

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

Divides first operand by the second int a = 12, b = 6;


Division /
operand int c = a/b; // c = 2

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.

Name Symbol Description Example

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++

Name Symbol Description Example

// 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.

Name Symbol Description Example

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++

Name Symbol Description Example

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.

Namemultiply Symbol Description Example

Assignment Assigns the value on the right to the variable on int a = 2;


=
Operator the left // a = 2

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

6) Ternary or Conditional Operators(?:)


This operator returns the value based on the condition.
Expression1? Expression2: Expression3

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++

// CPP Program to demonstrate the Conditional Operators


#include <iostream>
using namespace std;

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)

are executed, the control flow.

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):

!(x > 2) → false


(x > y) && (y > 0) → true
(x < y) && (y > 0) → false
(x < y) || (y > 0) → true

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!

1.1.2 if, if-else and else if

The if conditional has the form:

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.

Here is an example using these control structures:

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

int x = 2; int y = 6; then the output is y is greater than x. If we replace the


lines with

int x = 2; int y = 2; then the output is x


and y are equal.

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.

Here is an example using switch-case:

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.

1.2.1 while and do-while

The while loop has a form similar to the if conditional:

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 }

This program will print x is 10.

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:

for(initialization; condition; incrementation)


{
statement1 statement2

}

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

for(initialization; condition; incrementation)


{
statement1 statement2

}

we can write an equivalent while loop as

initialization while(condition)
{
statement1 statement2

incrementation
}

Using our example above,

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.

1.3 Nested Control Structures

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.

Here is an example using nesting if conditionals:

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.

Here is an example using nested loops:

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

The general form of a C++ function definition is as follows −

return_type function_name( parameter list ) {


body of the 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 −

// function returning the max between two numbers


34
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++

int max(int num1, int num2) {


// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

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.

A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), following is the function declaration −

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so following is also
valid declaration −

int max(int, int);

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;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2) {
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
36
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
result = num2;

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 −

Max value is : 200


Function Arguments

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 −

Sr.No Call Type & Description

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.

Default Values for Parameters

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;

int sum(int a, int b = 20) {


int result;
result = a + b;

return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
38
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
cout << "Total value is :" << result << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −

Total value is :300


Total value is :120
TYPE OF FUNCTION
Functions are broadly classified into several types based on their characteristics and purposes. Here are some
common types of functions:

1. Built-in Functions:

These are standard functions provided by programming languages or software libraries.


Examples include print() in Python, Math.random() in JavaScript, or sqrt() in C++.

2. User-Defined Functions:

Functions created by the programmer to perform specific tasks.


These functions enhance code modularity and reusability.

3. Recursive Functions:

Functions that call themselves, either directly or indirectly.


Recursive functions are often used in solving problems that can be broken down into smaller, similar sub-
problems.
Example:
#include <iostream>
using namespace std;

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;
}

4. Anonymous Functions (Lambda Functions):

Functions without a formal name.


Often used for short, simple operations and passed as arguments to higher-order functions.
In C++, you declare a lambda function using the following syntax:
[capture](parameters) -> return_type {
// Function body
}
Example:
#include <iostream>

int main() {
// Declare and use a lambda function
auto add = [](int a, int b) -> int {
return a + b;
};

// Call the lambda function


int result = add(3, 4);

// Print the result


std::cout << "Result: " << result << std::endl;

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. }

APPLY ARRAY IN C++

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:

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of three integers, you could write:

int myNum[3] = {10, 20, 30};

Array Initialization

Access the Elements of an Array

You access an array element by referring to the index number inside square brackets [].

This statement accesses the value of the first element in cars:

#include <iostream>

#include <string>

using namespace std;

int main() {

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

cout << cars[0];

return 0;

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element

To change the value of a specific element, refer to the index number:

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.

The following example outputs all elements in the cars array:

#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:

1. One Dimensional Arrays (1D Array)


2. Multidimensional Arrays
1. One Dimensional Array in C++
The One-dimensional arrays, also known as 1-D arrays in C++ are those arrays that have only one
dimension.

Syntax of 1D Array in C++

array_name [size];

45
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++

Example of 1D Array in C++

// C++ Program to illustrate the use of 1D array


#include <iostream>
Using namespace std;
int main()
{

// 1d array declaration
int arr[5];

// 1d array initialization using for loop


for (int i = 0; i < 5; i++) {
arr[i] = i * i - 2 * i + 1;
}

46
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++

Cout<<"Elements of Array: ";


// printing 1d array by traversing using for loop
for (int i = 0; i < 5; i++) {
Cout<< arr[i];
}
return 0;
}

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 in C++

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.

Syntax of 2D Array in C++

array_name[size1] [size2];

Here,

• size1: Size of the first dimension.


• size2: Size of the second dimension.

47
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++

Example of 2D Array in C++

// C++ Program to illustrate 2d array


#include <iostream>

int main()
{

// declaring and initializing 2d array


int arr[2][3] = { 10, 20, 30, 40, 50, 60 };

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

B. Three-Dimensional Array in C++

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.

Syntax of 3D Array in C++

array_name [size1] [size2] [size3];

49
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++

Example of 3D Array c++

// C++ Program to illustrate the 3d array


#include <iostream>

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++

Learning outcome 2. Apply OOP Concepts

C++ What is OOP?

OOP stands for Object-Oriented Programming.

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.

C++ What are Classes and Objects?

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

Apple, Banana, Mango

Another example: class: Car

Objects: Volvo, Audi, Toyota

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and functions from the class.

C++ Classes/Objects

C++ is an object-oriented programming language.

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

To create a class, use the class keyword:

Example

Create a class called "MyClass":

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

✓ Advantages of using OOP

Object-oriented programming has several advantages over procedural programming:

• OOP is faster and easier to execute


• OOP provides a clear structure for the programs
• OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the code easier to
maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and shorter development
time

✓ Description of key terms

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

Create an object called "myObj" and access the attributes:

#include <iostream>
#include <string>
using namespace std;

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
55
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
myObj.myString = "Some text";

// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

Class Methods

Methods are functions that belongs to the class.

There are two ways to define functions that belongs to a class:

• Inside class definition


• Outside class definition

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;

class MyClass { // The class


public: // Access specifier
void myMethod() { // Method/function
cout << "Hello World!";
}
};

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;

class MyClass { // The class


public: // Access specifier
void myMethod(); // Method/function declaration
};

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}

Parameters

You can also add parameters:

#include <iostream>
using namespace std;

class Car {
public:
int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {


57
Prepared by Fidèle NDAYISHIMIYE
Fundamental of c++
return 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 C++, there are three access specifiers:

• public - members are accessible from outside the class


• private - members cannot be accessed (or viewed) from outside the class
• protected - members cannot be accessed from outside the class, however, they can be accessed in
inherited classes. You will learn more about Inheritance later.

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++

// Another Parameterized Constructor


MyClass(int value1, int value2) {
// Initialization code with two parameters
}
};
✓ Static:
static is a keyword in C++ used to declare members (variables or functions) that belong to the class rather
than an instance of the class.
Static members are shared among all instances of the class.
Static variables are initialized only once and retain their values across different instances.
Static functions can be called without creating an instance of the class.
Member Variable:
Member variables are variables declared within a class.
They represent the attributes or properties of objects created from that class.
Member variables can be of various data types, and each object of the class has its own copy of these variables.
Member Function:
Member functions are functions defined within a class.
They operate on the data members of the class and encapsulate the behavior of the class.
Member functions can be called using an instance of the class.

✓ 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
}

void constFunction() const {


// Code that does not modify object's state
}
};
In the context of member functions, the const qualifier at the end of a function declaration indicates that the
function will not modify the object's state.

64
Prepared by Fidèle NDAYISHIMIYE

You might also like