0% found this document useful (0 votes)
14 views156 pages

Session1 2 3 4

The document provides an introduction to C++, a compiled, cross-platform programming language developed as an extension of C, emphasizing the importance of compiling and executing C++ code. It covers fundamental concepts such as variables, data types, syntax, and the use of comments, as well as practical examples for writing and running simple C++ programs. Additionally, it outlines the requirements for setting up a C++ development environment, including the use of IDEs and compilers.
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)
14 views156 pages

Session1 2 3 4

The document provides an introduction to C++, a compiled, cross-platform programming language developed as an extension of C, emphasizing the importance of compiling and executing C++ code. It covers fundamental concepts such as variables, data types, syntax, and the use of comments, as well as practical examples for writing and running simple C++ programs. Additionally, it outlines the requirements for setting up a C++ development environment, including the use of IDEs and compilers.
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/ 156

From zero to hero

1
► C++ is a compiled language. That means that to get a program
to run, you must first translate it from the human-readable
form to something a machine can “understand.” That
translation is done by a program called a compiler.

2
► it is important to know how to compile C++ program codes and how
to execute them. When we write code, we write it in a high-level
language that machines can't understand, known as source code.
The code that machines can understand & execute is in binary form
(0's and 1's) and is known as machine code, object code, or
executable code.
► Translating source code (high-level language code) into
machine-readable code consists of the following four processes that
we will learn in detail as we move through the course of this article:
► Pre-processing the source code
► Compiling the source code
► Assembling the compiled file
► Linking the object code file to create an executable file

3
► What is C++?
► C++ is a cross-platform language that can be used to create high-performance
applications.
► C++ was developed by Bjarne Stroustrup, as an extension to the C language.
► C++ gives programmers a high level of control over system resources and
memory.
► The language was updated 4 major times in 2011, 2014, 2017, and 2020 to
C++11, C++14, C++17, C++20.

4
► Difference between C and C++
► C++ was developed as an extension of C, and both languages have almost the
same syntax.
► The main difference between C and C++ is that C++ support classes and
objects, while C does not.

5
► To start using C++, you need two things:
► A text editor, like Notepad, to write C++ code
► A compiler, like GCC, to translate the C++ code into a language that the
computer will understand

6
► C++ Install IDE
► An IDE (Integrated Development Environment) is used to edit AND compile the
code.
► Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all
free, and they can be used to both edit and debug C++ code.
► Note: Web-based IDE's can work as well, but functionality is limited.
► Download the mingw-setup.exe file, which will install the text editor
with a compiler.

7
create our first C++ file.
Open Codeblocks and go to File > New > Empty File.
Write the following C++ code and save the file
as myfirstprogram.cpp (File > Save File as):

8
► #include <iostream>
using namespace std;

int main()
► {
cout << "Hello World!";
return 0;
}
► Line 1: #include <iostream> is a header file library that lets us work
with input and output objects, such as cout (used in line 5). Header files
add functionality to C++ programs
► Line 2: using namespace std means that we can use names for objects
and variables from the standard library.
9
Line 3: A blank line. C++ ignores white space. But we use it to make the code more
readable.

Line 4: Another thing that always appear in a C++ program, is int main(). This is
called a function. Any code inside its curly brackets {} will be executed.

Line 5: cout (pronounced "see-out") is an object used together with the insertion
operator (<<) to output/print text. In our example it will output "Hello World!".

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }

Remember: The compiler ignores white spaces. However, multiple lines makes the
code more readable.

Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket } to actually end the main
function
10
Omitting Namespace

► You might see some C++ programs that runs without the standard
namespace library. The using namespace std line can be omitted and
replaced with the std keyword, followed by the :: operator for some
objects:

► #include <iostream>

int main() {
std::cout << "Hello World!";
return 0;
}

► Note: It is up to you if you want to include the standard namespace library or


not.
11
12
C++ Output
► The cout object, together with the << operator, is used to output values/print text:
► You can add as many cout objects as you want. However, note that it does not insert a
new line at the end of the output:
► #include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
cout << "I am dancing";
return 0;
}
► Note: The symbol << is called insertion operation and output operator.
► The insertion operator << is the one we usually use for output, as in:
► cout << "This is output" << end;
► It gets its name from the idea of inserting data into the output stream.

► >> Operator called extraction operator. The extraction operator (>>), which is preprogrammed for
13
all standard C++ data types, is the easiest way to get bytes from an input stream object.
New Lines

► To insert a new line, you can use the \n character:


► #include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}

► Two \n characters after each other will


create a blank line:
14
Another way to insert a new line, is with the endl manipulator:

► #include <iostream>
using namespace std;

int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}

15
Both \n and endl are used to break lines. However, \n is
most used.
But what is \n exactly?
The newline character (\n) is called an escape
sequence,
and it forces the cursor to change its position to the
beginning of the next line on the screen. This results in
a new line.

16
Escape sequence Character represented

\a Alert (bell, alarm)

\b Backspace

\f Form feed (new page)

\n New-line

\r Carriage return

\t Horizontal tab

\v Vertical tab

\' Single quotation mark

\" Double quotation mark

\? Question mark
17

\\ Backslash
C++ Comments

► Comments can be used to explain C++ code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.
Comments can be singled-lined or multi-lined.
► Single-line comments start with two forward slashes (//).
► // This is a comment
cout << "Hello World!";
► ---------------------
► /* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";

18
C++ Variables
► imagine that I ask you to remember the number 5, and then I ask you to also memorize the number
2 at the same time.
► You have just stored two different values in your memory (5 and 2).
► Now, if I ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is
5+1) and 2 in your memory.
► Then we could, for example, subtract these values and obtain 4 as result.
► The whole process described above is a simile of what a computer can do with two variables. The
same process can be expressed in C++ with the following set of statements:

a = 5;
b = 2;
a = a + 1;
result = a - b;

19
► We can now define variable as a portion of memory to store a value.
► Each variable needs a name that identifies it and distinguishes it from the
others.

► For example, in the previous code the variable names were a, b, and result, but we could
have called the variables any names we could have come up with, as long as
they were valid C++ identifiers.

20
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with
different keywords), for example:
•int - stores integers (whole numbers), without decimals,
such as 123 or -123

•double - stores floating point numbers, with decimals, such


as 19.99 or -19.99

•char - stores single characters, such as 'a' or 'B'. Char


values are surrounded by single quotes

•string - stores text, such as "Hello World". String values


are surrounded by double quotes 21

•bool - stores values with two states: true or false


Declaring (Creating) Variables
► Syntax
► type variableName = value;

► Example

► int myNum = 15;


cout << myNum; or

► int myNum;
myNum = 15;
cout << myNum;

22
Note that if you assign a new value to an
existing variable, it will overwrite the
previous value:
► int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

► int myNum = 5; // Integer (whole number without decimals)


double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

23
Basic Data Types

Data Size Description


Type
boolean 1 byte Stores true or false values
char 1 byte Stores a single character/letter/number, or ASCII values
int 2 or 4 Stores whole numbers, without decimals
bytes
float 4 bytes Stores fractional numbers, containing one or more
decimals. Sufficient for storing 6-7 decimal digits
double 8 bytes Stores fractional numbers, containing one or more
decimals. Sufficient for storing 15 decimal digits

24
e.g.s
► int myNum = 1000;
cout << myNum;
► ---------------------------------------
► float myNum = 5.75;
cout << myNum;
► --------------------
► double myNum = 19.99;
cout << myNum;
► ------------------------
► Note:
float vs. double
The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of float is only six
25

or seven decimal digits, while double variables have a precision of about


Scientific Numbers
► A floating point number can also be a
scientific number with an "e" to indicate
the power of 10:
► float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;

26
C++ Boolean Data Types

A boolean data type is declared with the bool keyword and can
only take the values true or false.
When the value is returned, true = 1 and false = 0.

bool isMeSmart = true;


bool isMeFool = false;

cout << isMeSmart; // Outputs 1 (true)


cout << isMeFool; // Outputs 0 (false)

Boolean values are mostly used for conditional testing

27
C++ Character Data Types

The char data type is used to store a single character.


The character must be surrounded by single quotes, like 'A' or 'c’:

char myGrade = 'B';


cout << myGrade;

28
C++ String Data Types
The string type is used to store a sequence of characters (text).
`This is not a built-in type, but it behaves like one in its most basic
String values must be surrounded by double quotes:
string greeting = "Hello";
cout << greeting;
To use strings,
you must include an additional header file in the source code,
the <string> library:
// Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";
29
// Output string value
cout << greeting;
► int myAge = 35;
cout << "I am " << myAge << " years old.";

► int x = 5;
int y = 6;
int sum = x + y;
cout << sum;

30
Create a variable named gg and assign the value 3567to

31
C++ Declare Multiple Variables

► To declare more than one variable of the same type, use a


comma-separated list
► int x = 5, y = 6, z = 50;
cout << x + y + z;

► One Value to Multiple Variables


► int x, y, z;
x = y = z = 50;
cout << x + y + z;

32
Identifiers
► All C++ variables must be identified with unique names.
► These unique names are called identifiers.

► A valid identifier is a sequence of one or more letters, digits, or underscore


characters (_).
► Spaces, punctuation marks, and symbols cannot be part of an identifier. In addition, identifiers shall
always begin with a letter.
► They can also begin with an underline character (_), but such identifiers are -on most cases-
considered reserved for compiler-specific keywords or external identifiers, as well as identifiers
containing two successive underscore characters anywhere.

► In no case can they begin with a digit.


► C++ uses a number of keywords to identify operations and data descriptions; therefore, identifiers
created by a programmer cannot match these keywords.
► The standard reserved keywords that cannot be used for programmer created identifiers are:
33
► alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break,
case, catch, char, char16_t, char32_t, class, compl, const, constexpr,
const_cast, continue, decltype, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern, false, float, for,
friend, goto, if, inline, int, long, mutable, namespace, new,
noexcept, not, not_eq, nullptr, operator, or, or_eq, private,
protected, public, register, reinterpret_cast, return, short, signed,
sizeof, static, static_assert, static_cast, struct, switch, template,
this, thread_local, throw, true, try, typedef, typeid, typename,
union, unsigned, using, virtual, void, volatile, wchar_t, while, xor,
xor_eq

► Specific compilers may also have additional specific reserved keywords.

Very important: The C++ language is a "case sensitive" language

► . That means that an identifier written in capital letters is not equivalent to another
one with the same name but written in small letters. T

► hus, for example, the RESULT variable is not the same as the result variable or
the Result variable. These are three different identifiers identifiying three different
variables.
34
The general rules for naming variables
are:or variable naming convension
The general rules for naming variables are:

•Names can contain letters, digits and underscores

•Names must begin with a letter or an underscore (_)

•Names are case sensitive (myVar and myvar are different variables)

•Names cannot contain whitespaces or special characters like !, #, %, etc.

•Reserved words (like C++ keywords, such as int) cannot be used as names

35
C++ Constants
use the const keyword (this will declare
the variable as "constant", which
means unchangeable and
read-only):
► const int myNum = 15; // myNum will always be
15
myNum = 10; // error: assignment of read-only
variable 'myNum'

36
Important note
► When you declare a constant variable, it must be assigned
with a value:
► Literals
► Literals are the most obvious kind of constants. They are used to express
particular values within the source code of a program.

These literal constants have a type, just like variables. By default, integer literals are of type
int. However, certain suffixes may be appended to an integer literal to specify a different integer type:

Unsigned may be combined with any of the other two in any order to form unsigned long or unsigned long long.
Suffix Type modifier
u or U unsigned
l or L long
ll or LL long long 37
Preprocessor definitions (#define)

Another mechanism to name constant values is the use of preprocessor definitions.


They have the following form:

#define identifier replacement

After this directive, any occurrence of identifier in the code is interpreted


as replacement,
where replacement is any sequence of characters (until the end of the line).
This replacement is performed by the preprocessor, and
happens before the program is compiled,
thus causing a sort of blind replacement:
the validity of the types or syntax involved is not checked in any way.
38
39
What is your observation in preprocessor
definitons ?

40
Ans is …
Note that
the #define lines are preprocessor directives,
and as such are single-line instructions that -unlike C++
statements-

do not require semicolons (;) at the end;


the directive extends automatically until the end of the line
. If a semicolon is included in the line,

it is part of the replacement sequence and 41

is also included in all replaced occurrences.


Operators
► Assignment operator (=)
► The assignment operator assigns a value to a
variable.
► x = 5;
► This statement assigns the integer value 5 to the
variable x. The assignment operation always takes
place from right to left, and never the other way
around:
► x=y
► This statement assigns to variable x the value
contained in variable y
42
43
y = 2 + (x = 5);
Or

x = 5; y = 2 + x;

x = y = z = 5; is this valid ?

It assigns 5 to the all three variables: x, y and z; always from right-to-left.

44
Arithmetic operators ( +, -, *, /, % )

operator description
+ addition
- subtraction
* multiplication
/ division
% modulo

45
Operations of addition, subtraction, multiplication and division
correspond literally to their respective mathematical operators.
The last one, modulo operator, represented by a percentage
sign
(%), gives the remainder of a division of two values. For
example:

x = 11 % 3;
results in variable x containing the value 2, since dividing 11 by 3 results in 3, with
a remainder of 2.

46
Compound assignment (+=, -=, *=, /=, %=,
>>=, <<=, &=, ^=, |=)

xpression equivalent to...


y += x; y = y + x;
x -= 5; x = x - 5;
x /= y; x = x / y;
price *= units + 1; price = price * (units+1);

47
1
2
// compound assignment operators
3 #include <iostream>
4
5 using namespace std;
6
7
int main ()
8 {
9
10 int a, b=3; a = b;
11 a+=2; // equivalent to a=a+2
cout << a;
Return 0;
}

48
Increment and decrement (++, --)
some expression can be shortened
even more: the increase operator
(++) and the decrease operator (--)
increase or reduce by one the value
stored in a variable. They are
equivalent to +=1 and to -=1,
respectively. 1 ++x;
2 x+=1;
Thus:
3 x=x+1; 49
Relational and comparison operators ( ==,
!=, >, <, >=, <= )
operator description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

(7 == 5) // evaluates to false
(5 > 4) // evaluates to true
(3 != 2) // evaluates to true
(6 >= 6) // evaluates to true 50

(5 < 5) // evaluates to false


Logical operators ( !, &&, || )

operator ! is the C++ operator for the Boolean operation NOT


The operator && corresponds to the Boolean logical operation AND
The operator || corresponds to the Boolean logical operation OR,

,
.

51
Conditional ternary operator ( ? :)

► The conditional operator evaluates an


expression, returning one value if that
expression evaluates to true, and a different
one if the expression evaluates as false. Its
syntax is:
condition ? result1 : result2
► If(a>b)?a is big :b is big

52
Comma operator ( , )
The comma operator (,) is used to separate
two or more expressions that are
included where only one expression is
expected. When the set of expressions
has to be evaluated for a value, only the
right-most expression is considered.
1 a = (b=3, b+2); 53
Bitwise operators ( &, |, ^, ~, <<, >> )
operator asm equivalent description
& AND Bitwise AND
Bitwise inclusive
| OR
OR
Bitwise exclusive
^ XOR
OR
Unary
~ NOT complement (bit
inversion)
<< SHL Shift bits left 54

>> SHR Shift bits right


Explicit type casting operator

► Type casting operators allow to convert a value of a given


type to another type. There are several ways to do this in
C++. The simplest one, which has been inherited from the
C language, is to precede the expression to be converted
by the new type enclosed between parentheses (()):
int i;
float f = 3.14;
i = (int) f;

i = int (f);

55
sizeof

► This operator accepts one


parameter, which can be either a
type or a variable, and returns the
size in bytes of that type or object:
x = sizeof (char)

56
Basic Input/Output
1 cout << "First sentence." << endl;
2 cout << "Second sentence." << endl;

int age;
cin >> age;

57
58
Statements and flow control
► Selection statements: if (x == 100)
cout << "x is 100";
► if (condition) statement

► If you want to include more than a single


statement to be executed when the condition is
fulfilled, these statements shall be enclosed in
braces ({}), forming a block:
if (x == 100)
{
cout << "x is ";
cout << x;
} 59
Selection statements with if can also specify what
happens when the condition is not fulfilled, by using
the else keyword to introduce an alternative statement.
Its syntax is:
if (condition) statement1 else statement2
where statement1 is executed in case condition is true,
and in case it is not, statement2 is executed.
60
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
61
► Several if + else structures can be
concatenated with the intention of
checking a range of values
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0"; 62
Iteration statements (loops)
Loops repeat a statement a certain number of times, or
while a condition is fulfilled
. They are introduced by the keywords while, do, and for.
The while loop
The simplest kind of loop is the while-loop. Its syntax is:
while (expression) statement
The while-loop simply repeats statement while expression is true.
If, after any execution of statement, expression is no longer true, the loop
ends
, and
the program continues right after the loop.
For example, let's have a look at a countdown using a while-loop:
63
while (condition) {
// code block to be executed
}
► int i = 0;
► while (i < 5) {
► cout << i << "\n";
► i++;
► }

64
65
The do-while loop
► Do
► statement
► ……..
► …..
► while (condition);
► It behaves like a while-loop,

► except that condition is evaluated after the execution of statement instead of


before,

► guaranteeing at least one execution of statement, even if condition is never


fulfilled.

► For example, the following example program echoes any text the user introduces
until the user enters goodbye:

66
do {
// code block to be executed
}
while (condition);
► int i = 0;
► do {
► cout << i << "\n";
► i++;
► }
► while (i < 5);

67
68
The for loop

Its syntax is:

for (initialization; condition; increase) statement;

69
Continued…

Like the while-loop, this loop repeats statement while condition is true.

But, in addition, the for loop provides specific locations to contain an initialization and

an increase expression, executed before the loop begins the first time, and
after each iteration, respectively.
Therefore, it is especially useful to use counter variables as condition.

It works in the following way:

1.initialization is executed. Generally, this declares a counter variable, and sets it to some initial value.
2. This is executed a single time, at the beginning of the loop.
2.condition is checked. If it is true, the loop continues; otherwise, the loop ends, and
3. statement is skipped, going directly to step 5.
3.statement is executed. As usual, it can be either a single statement or a block enclosed in curly braces { }.
4.increase is executed, and the loop gets back to step 2.
5.the loop ends: execution continues by the next statement after it.
70
eg

// countdown using a for loop


#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "liftoff!\n"; 71

return 0;
#include <iostream>
using namespace std;
intThe
mainbreak
() statement
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
} } }

72
The continue statement
► The continue statement causes the program to skip the rest of
the loop in the current iteration, as if the end of the statement
block had been reached, causing it to jump to the start of the
following iteration. For example, let's skip number 5 in our
countdown:
► // continue loop example
► #include <iostream>
► using namespace std;

► int main ()
► {
► for (int n=10; n>0; n--) {
► if (n==5) continue;
► cout << n << ", ";
► }
► cout << "liftoff!\n"; 73

► }
The goto statement
► goto allows to make an absolute jump to another point in the
program. This unconditional jump ignores nesting levels, and does not
cause any automatic stack unwinding. Therefore, it is a feature to use
with care, and preferably within the same block of statements,
especially in the presence of local variables.

► The destination point is identified by a label, which is then used as an


argument for the goto statement. A label is made of a valid identifier
followed by a colon (:).

► goto is generally deemed a low-level feature, with no particular use


cases in modern higher-level programming paradigms generally used
with C++. But, just as an example, here is a version of our countdown
loop using goto:
74
eg
► // goto loop example
► #include <iostream>
► using namespace std;

► int main ()
► {
► int n=10;
► mylabel:
► cout << n << ", ";
► n--;
► if (n>0) goto mylabel;
► cout << "liftoff!\n";
► }
75
Another selection statement: switch.
► The syntax of the switch statement is a bit peculiar. Its purpose is to check for a value among a
number of possible constant expressions. It is something similar to concatenating if-else
statements, but limited to constant expressions. Its most typical syntax is:
► code>switch (expression)
► {
► case constant1:
► group-of-statements-1;
► break;
► case constant2:
► group-of-statements-2;
► break;
► default:
► default-group-of-statements
► }/code>
76
► This is how it works:

► The switch expression is evaluated once


► The value of the expression is compared with the values of each case
► If there is a match, the associated block of code is executed
► The break and default keywords are optional, and will be described later in
this chapter

77
► int day = 4;
► switch (day) {
► case 1:
► cout << "Monday";
► break;
► case 2:
► cout << "Tuesday";
► break;
► case 3:
► cout << "Wednesday";
► break;
► case 4:
► cout << "Thursday";
► break;
► case 5:
► cout << "Friday";
► break;
► case 6:
► cout << "Saturday";
► break;
► case 7:
► cout << "Sunday";
► break;
78
► }
► // Outputs "Thursday" (day 4)
The default Keyword
The default keyword specifies some code to run if
there is no case match:
► int day = 4;
► switch (day) {
► case 6:
► cout << "Today is Saturday";
► break;
► case 7:
► cout << "Today is Sunday";
► break;
► default:
► cout << "Looking forward to the Weekend";
► }
79
Arrays

► An array is a series of elements of the same type placed in contiguous


memory locations that can be individually referenced by adding an index to a
unique identifier.
► 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:

80
► string cars[4];
► string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
► int myNum[3] = {10, 20, 30};
► Access the Elements of an Array
► string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
► cout << cars[0];
► // Outputs Volvo

81
Functions

► A function is a block of code which only runs when it is called.

► You can pass data, known as parameters, into a function.

► Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
► void myFunction() {
► // code to be executed
► }

82
► // Create a function
► void myFunction() {
► cout << "I just got executed!";
► }

► int main() {
► myFunction(); // call the function
► return 0;
► }

► // Outputs "I just got executed!"

83
► A function can be called multiple times:
► void myFunction() {
cout << "I just got executed!\n";
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

84
► Function Declaration and Definition
► A C++ function consist of two parts:
► Declaration: the return type, the name of the function, and parameters (if
any)
► Definition: the body of the function (code to be executed)
► void myFunction() { // declaration
// the body of the function (definition)
}

85
► int main() {
myFunction();
return 0;
}

void myFunction() {
cout << "I just got executed!";
}

86
► However, it is possible to separate the declaration and the definition of the
function - for code optimization.

► You will often see C++ programs that have function declaration above main(),
and function definition below main(). This will make the code better
organized and easier to read:

87
► // Function declaration
► void myFunction();

► // The main method


► int main() {
► myFunction(); // call the function
► return 0;
► }

► // Function definition
► void myFunction() {
► cout << "I just got executed!";
► }

88
C++ Function Parameters

► Parameters and Arguments


► Information can be passed to functions as a parameter. Parameters act as
variables inside the function.

► Parameters are specified after the function name, inside the parentheses.
You can add as many parameters as you want, just separate them with a
comma:

89
► Syntax
► void functionName(parameter1, parameter2, parameter3) {
► // code to be executed
► }
► The following example has a function that takes a string called fname as parameter.
When the function is called, we pass along a first name, which is used inside the
function to print the full name:
► void myFunction(string fname) {
► cout << fname << " Refsnes\n";
► }

► int main() {
► myFunction(“anju");
► myFunction(“manju");
► myFunction("Anu");
► return 0;
► } 90
The Return Keyword / call by value

► Return Values
► The void keyword, used in the previous examples, indicates that the function should not
return a value. If you want the function to return a value, you can use a data type (such as
int, string, etc.) instead of void, and use the return keyword inside the function:
► `int myFunction(int x) {
► return 5 + x;
► }

► int main() {
► cout << myFunction(3);
► return 0;
► }

91
92
Functions - Pass By Reference
► Pass By Reference
► void swapNums(int &x, int &y) {
► int z = x;
► x = y;
► y = z;
► }
► int main() {
► int firstNum = 10;
► int secondNum = 20;
► cout << "Before swap: " << "\n";
► cout << firstNum << secondNum << "\n";

► // Call the function, which will change the values of firstNum and secondNum
► swapNums(firstNum, secondNum);

► cout << "After swap: " << "\n";


► cout << firstNum << secondNum << "\n";

93
► return 0;
► }
Function Overloading
With function overloading, multiple functions can have the same name with different
parameters : ► int myFunction(int x)
► float myFunction(float x)
► double myFunction(double x, double y)
► Example
► int plusFuncInt(int x, int y) {
► return x + y;
► }

► double plusFuncDouble(double x, double y) {


► return x + y;
► }
► int main() {
► int myNum1 = plusFuncInt(8, 5);
► double myNum2 = plusFuncDouble(4.3, 6.26);
► cout << "Int: " << myNum1 << "\n";
► cout << "Double: " << myNum2;
► return 0; 94

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

► 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

95
► 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:

96
97
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.

► 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. 98
Create a Class
To create a class, use the class keyword:
► class MyClass { // The class
► public: // Access specifier
► int regno; // Attribute (int variable)
► string name; // Attribute (string variable)
► };
► The class keyword is used to create a class called MyClass.
► The public keyword is an access specifier, which specifies that members
(attributes and methods) of the class are accessible from outside the class.
You will learn more about access specifiers later.
► Inside the class, there is an integer variable myNum and a string variable
myString. When variables are declared within a class, they are called
attributes.
► At last, end the class definition with a semicolon ;.

99
Create an Object
► 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:
► 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;
► myObj.myString = "Some text";
► // Print attribute values
► cout << myObj.myNum << "\n";
► cout << myObj.myString;
► return 0; 100

► }
Multiple Objects you can create multiple objects of one class:
► // Create a Car class with some attributes
► class Car {
► public:
► string brand;
► string model;
► int year; };
► int main() {
► // Create an object of Car
► Car carObj1;
► carObj1.brand = "BMW";
► carObj1.model = "X5";
► carObj1.year = 1999;
► // Create another object of Car
► Car carObj2;
► carObj2.brand = "Ford";
► carObj2.model = "Mustang";
► carObj2.year = 1969;
► // Print attribute values
► cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
► cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
101
► 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 (.):

102
► class MyClass { // The class
► public: // Access specifier
► void myMethod() { // Method/function defined inside the class
► cout << "Hello World!";
► }
► };

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

103
Usage of :: or
► 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 specifiying the name of the class,
followed the scope resolution :: operator,
followed by the name of the function:

104
eg
► 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; 105

► }
Parameters You can also add parameters:
► #include <iostream>
using namespace std;

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

int Car::speed(int maxSpeed) {


return maxSpeed;
}

int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
106
Difference between Structure and Class in
C++

► In C++, the structure is the same as the class with some differences. Security
is the most important thing for both structure and class. A structure is not
safe because it could not hide its implementation details from the end-user,
whereas a class is secure as it may hide its programming and design details

107
► A structure is a grouping of variables of various data types referenced by the same name. A
structure declaration serves as a template for creating an instance of the structure.
► Syntax:
► Struct Structurename
► {
► Struct_member1;
► Struct_member2;
► Struct_member3;
► .
► .
► .
► Struct_memberN;
► };
108
► A class in C++ is similar to a C structure in that it consists of a list of data members and a
set of operations performed on the class. In other words, a class is the building block of
Object-Oriented programming. It is a user-defined object type with its own set of data
members and member functions that can be accessed and used by creating a class instance.
A C++ class is similar to an object's blueprint.
► Syntax:
► class class_name
► {
► // private data members and member functions.
► Access specifier;
► Data member;
► Member functions (member list){ . . }
► };
109
Main differences between the structure and
class

► By default, all the members of the structure are public. In contrast, all members of
the class are private.
► The structure will automatically initialize its members. In contrast, constructors and
destructors are used to initialize the class members.
► When a structure is implemented, memory allocates on a stack. In contrast, memory
is allocated on the heap in class.
► Variables in a structure cannot be initialized during the declaration, but they can be
done in a class.
► There can be no null values in any structure member. On the other hand, the class
variables may have null values.
► A structure is a value type, while a class is a reference type.
► Operators to work on the new data form can be described using a special method.

110
Features Structure Class
Definition A structure is a grouping of variables of In C++, a class is defined as a collection of
various data types referenced by the same related variables and functions contained within
name. a single structure.
Basic If no access specifier is specified, all If no access specifier is defined, all members
members are set to 'public'. are set to 'private'.

Declaration struct structure_name{ type struct_member class class_name{ data member; member
1; type struct_member 2; type struct_member function; };
3; . type struct_memberN; };
Instance Structure instance is called the 'structure A class instance is called 'object'.
variable'.
Inheritance It does not support inheritance. It supports inheritance.

Memory Memory is allocated on the stack. Memory is allocated on the heap.


Allocated
Nature Value Type Reference Type
Purpose Grouping of data Data abstraction and further inheritance.

Usage It is used for smaller amounts of data. It is used for a huge amount of data.

Null values Not possible It may have null values.


111

Requires It may have only parameterized constructor. It may have all the types of constructors and
► Similarities
► The following are similarities between the structure and class:
► Both class and structure may declare any of their members private.
► Both class and structure support inheritance mechanisms.
► Both class and structure are syntactically identical in C++.
► A class's or structure's name may be used as a stand-alone type.

112
container class…
► A container class is a data type that is capable of holding a collection of items. In C++, container
classes can be implemented as a class, along with member functions to add, remove, and examine
items.
► As an example, I have two classes A and B. An object of B is a member of class A (container). What
is the best way to access data of container class (A) from the member class (object of B).

Also, I don't want to use inheritance (B -> A) as B is not logically derived from A.

113
► class first {
► public:
► void showf()
► { cout << "Hello from first class\n";
► } };
► // Container class
► class second {
► // creating object of first
► first f;
► public:
► // constructor
► second() {
► // calling function of first class
► f.showf();
► } };
► int main() {
► // creating object of second
114
► second s; }
115
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 ():

116
eg
► 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;
► } 117
Constructor Parameters or parameterized constructor
► Constructors can also take parameters (just like regular functions), which can be useful for setting initial values for attributes.
► class Car { // The class
► public: // Access specifier
► string brand; // Attribute
► string model; // Attribute
► int year; // Attribute
► Car(string x, string y, int z) { // Constructor with parameters
► brand = x;
► model = y;
► year = z;
► }
► };
► int main() {
► // Create Car objects and call the constructor with different values
► Car carObj1("BMW", "X5", 1999);
► Car carObj2("Ford", "Mustang", 1969);
► // Print values
► cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
► cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
118
► return 0;
► }
Just like functions, constructors can also be defined outside the class. First, declare
the constructor inside the class, and then define it outside of the class by specifying
the name of the class, followed by the scope resolution ::
► class Car { // The class

► public: // Access specifier

► string brand; // Attribute

► string model; // Attribute

► int year; // Attribute

► Car(string x, string y, int z); // Constructor declaration

► };

► // Constructor definition outside the class

► Car::Car(string x, string y, int z) {

► brand = x;

► model = y;

► year = z;

► }

► int main() {

► // Create Car objects and call the constructor with different values

► Car carObj1("BMW", "X5", 1999);

► Car carObj2("Ford", "Mustang", 1969);

► // Print values

► cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";

► cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";

► return 0;

► } 119
► class Car { // The class
► public: // Access specifier
► string brand; // Attribute
► string model; // Attribute
► int year; // Attribute
► Car(string x, string y, int z); // Constructor declaration
► };

► // Constructor definition outside the class


► Car::Car(string x, string y, int z) {
► brand = x;
► model = y;
► year = z;
► }

► int main() {
► // Create Car objects and call the constructor with different values
► Car carObj1("BMW", "X5", 1999);
► Car carObj2("Ford", "Mustang", 1969);

► // Print values
► cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
► cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
120
► return 0;
► }
Access Specifiers

► Already discussed …….

121
► 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.

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

123
Execute this and tell me the result
► If you try to access a private member, an error occurs:
► error: y is private
► Note: It is possible to access private members of a class using a public method
inside the same class. See the next chapter (Encapsulation) on how to do this.

► Tip: It is considered good practice to declare your class attributes as private


(as often as you can). This will reduce the possibility of yourself (or others) to
mess up the code. This is also the main ingredient of the Encapsulation
concept, which you will learn more about in the next chapter.

► Note: By default, all members of a class are private if you don't specify an
access specifier:
124
Encapsulation
► The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve
this, you must declare class variables/attributes as private (cannot be accessed from outside the class).
If you want others to read or modify the value of a private member, you can provide public get and set
methods.
► Access Private Members
► To access a private attribute, use public "get" and "set" methods:
► #include <iostream>
using namespace std;
class Employee {
private: // Private attribute
int salary;
public: // Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000); 125
cout << myObj.getSalary();
return 0;
} same prg in next slide
► #include <iostream>
using namespace std;

class Employee {
private:
// Private attribute
int salary;

public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};

int main() {
Employee myObj;
myObj.setSalary(50000); 126
cout << myObj.getSalary();
return 0;
Encapsulation?

► It is considered good practice to declare your class


attributes as private (as often as you can). Encapsulation
ensures better control of your data, because you (or
others) can change one part of the code without affecting
other parts
► Increased security of data

127
Syllabus

128
Inheritance
► The mechanism of deriving a new class from an existing class is called inheritance.
► The existing class is referred as base class and the new one is called derived class.
► The derived class inherits all capabilities of base class & also add new features to this class. But the base
class remains unchanged
► this feature supports code reusability.
► Once a class has been written and tested , it can be used by other programmers to suit their requirements.

► In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance
concept" into two categories:

► derived class (child) - the class that inherits from another class
► base class (parent) - the class being inherited from
► To inherit from a class, use the : symbol.

129
► Defining Derived Classes :

► class derived-class name : visibility mode base-


► class name
► {
► members of derived class
► };

130
eg. for single inheritance :
► #include<iostream.h>
► #include<conio.h>
► class emp
► {
► int no;
► char name[10];
► public:
► void get( )
► {
► cout<< "\n\nenter no & name \n";
► cin>>no;
► cin >>name;
► }
► void print( )
► {
► cout<<"\n\nname is "<< name;
► cout<<"\nno is " << no;
► } 131

► };
► class physic : public emp
► {
► float height,weight;
► public:
► void read( )
► { get( ) ;
► cin >> height >> weight; }
► void disp()
► {
► print();
► cout<<height;
► cout<<weight;}
132
► };
Continued……

► void main( )
► {
► physic p;
► clrscr();
► p.read();
► p.disp();
► getch();
► } 133
► Visibility Modes

► While deriving the new classes , the


visibility modes gives the total control over
the data members & methods of the base
class. The visibility mode may be private ,
public or protected.

134
Ambiguity Resolution In Inheritance

► The ambiguity error arises whenever a


data member and member function are
defined with a same name in both the base
& derived classes. The compiler cannot
distinguish between the member functions
of the two classes. To resolve this problem
scope resolution operator is used.

135
EG
► #include <iostream.h>
► class bas
► {
► int no;
► public:
► void get()
► { cin >> no;}

► void put()
► { cout << no;}
► };

136
Cont..
► class der : public bas
► {
► char name[10];
► public :
► void get()
► { cin >> name;}
► void put()
► {cout<<"\n name = "<<name ; }
};
137
Cont..
► void main()
► { der d;
► d.bas::get();
► d.get();
► d.bas::put();
► d.put();
► }

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
► https://cplusplus.com/doc/tutorial/variables/
► https://www.javatpoint.com/cpp-variable

156

You might also like