2 C++ Basics
2 C++ Basics
1
C++
• C++ is a statically typed, compiled, general-purpose, case-
sensitive, free-form programming language that supports
procedural, object-oriented, and generic programming.
• C++ is a superset of C.
2
Contd..
• Need of C++:
– In order to solve the complex problems and to model the real world
perfectly, C++ was developed.
3
Contd..
• Uses of C++:
– used to write device driver programs.
– C++ is widely used for teaching and research because it is clean enough
for successful teaching of basic concepts.
5
Contd..
• Program 1: Program to print a sentence on the screen.
6
Contd…
• Output:
7
Contd..
• Program2: A Program to add two number and output the sum
8
Contd….
• Output:
9
Character set and Tokens
• Character set :
– Character set is a set of valid characters that a language can recognize. A
character represents any letter, digits, or any other sign.
10
Contd..
• Tokens:
– The smallest individual unit in a program is known as tokens.
C++ has the following tokens:
• Keywords
• Identifiers
• Constants
• Operators
• Special symbols.
11
Contd..
1. Keywords:
– keywords are the reserved words for special purpose and must not be
used as normal identifier names.
12
Contd..
2. Identifiers:
• Identifiers refers to the names of variable, functions, arrays, classes, etc.
• The following rule is used to create a identifier:
– identifier must start with a letter or underscore symbol (_), the rest of the characters
should be letters, digits or underscores
– legal identifiers:
x x1 x_1 _abc sum RateAveragE
– illegal identifiers, why?
13 3X %change data-1 my.identifier a(3)
– C++ is case sensitive:
MyVar and myvar are different identifiers
13
Contd..
3. Constants:
– Constants are the data items that never change their value during a
program run.
• character-constant
• floating-constant
• string-literal
14
Contd..
4. Operators: An operator is a symbol that tells the compiler to
perform specific mathematical or logical calculations on
operands(variables).
• Types of operators available in C++
– Assignment operator
– Arithmetic / Mathematical operator
– Increment Decrement operator
– Relational operator
– Logical operator
– Conditional or Ternary operator
– Binary operator
– Unary operator
15
Contd..
• Assignment operator :
– Assignment operator is used to copy value from right to left variable.
– Suppose we have, float X = 5, Y = 2;
Operator Name Description Example
X = Y, Now both X and Y
= Equal sign Copy value from right to left.
have 5
Plus Equal to operator will return
X += Y is similar to X = X
+= Plus Equal to the addition of right operand and
+ Y, now X is 7
left operand.
17
Contd..
• Relational operators: Relational operators are used for checking conditions
whether the given condition is true or false. If the condition is true, it will return non-
zero value, if the condition is false, it will return 0.
19
Contd..
• Conditional Operator ?:
– The conditional operator is also known as ternary operator. It is called
ternary operator because it takes three arguments. First is condition,
second and third is value. The conditional operator check the condition, if
condition is true, it will return second value, if condition is false, it will
return third value.
– Syntax :
• val = condition ? val1 : val2;
– Example :
int main()
{
int X=5,Y=2,lrg;
lrg = (X>Y) ? X : Y;
cout << "\nLargest number is : " << lrg;
}
Output : Largest number is : 5
20
Contd..
• Binary operator
– Binary operators are those operators that works with at least two operands
such as (Arithmetic operators) +, -, *, /, %.
• Unary operator
– Unary operators are those operators that works with single operands such
as (Increment or Decrement operators) ++ and --.
21
Contd..
5. Special Symbols: Escape characters are known as special symbols in C++. An
escape sequence is represented by a backslash (\) followed by one or more characters.
Following table lists the C++ Escape Sequences :
22
C++ Data Types
• A data type defines a set of values that a variable can store along with a set of
• Each and every variable and constants that we are using in our program must
• The reason behind it is that, each and every variable/constant must be placed
the compiler.
23
C++ Data Types
• The various data types provided by C++ are:
24
C++ Data Types
25
Contd..
• Fundamental data types( built-in/basic data type):
• Several of the basic types can be modified using one or more of these
type modifiers −
– signed
– unsigned
– short
– long
26
Contd..
• The following table shows the variable type, how much memory
it takes to store the value in memory, and what is maximum and
minimum value which can be stored in such type of variables.
27
Contd..
28
Contd..
• The size of variables might be different from those shown in the
above table, depending on the compiler and the computer you are
using.
29
Contd..
• Program:
30
Contd..
• Output:
31
Contd..
• Derived data types:
– Data types that are derived from the built in data types are known as
derived data types.
• Functions
32
Contd..
• User defined data types:
– The data types that are defined by the user as per their need is called user
defined data types,
• Unions
• Enumerations and
• classes
33
Contd..
• Example Program :
34
35
Type Conversion
• Converting an expression of a given type into another type is
known as type conversion.
36
Contd…
• Implicit (Automatic) Type conversion:
– An implicit type conversion is a conversion performed by the
compiler without programmer's intervention.
• promotions and
• conversions.
37
Contd..
• Promotion
– Whenever a value from one type is converted into a
value of a larger similar data type, this is called
a promotion (or widening) For example, an int can be
widened into a long, or a float promoted into a double:
float y= 2.5, z;
z=x+y;
38
Contd..
• Conversion:
– When we convert a value from a larger type to a similar smaller
type, or between different types, this is called a numeric
conversion. For example:
• double d = 3; // convert integer 3 to a double (between different types)
39
Contd..
• Explicit type conversion(Type casting):
– Type casting is the forceful conversion form one type to another
type.
Here if we do not cast a into long, the result of sub-expression a*5 will be
50000 which is outside of the range of data type short int and causes the
program to produce wrong result. But this case automatic type conversion
is not done by the compiler and hence programmer needs to use explicit
type conversion to produce the right result.
41
Contd..
• Program:
42
Contd..
• Output:
43
Preprocessor Directives
• preprocessor directives are lines included in the code of programs
preceded by a hash sign (#).
• These lines are not program statements but directives for the
preprocessor.
– The preprocessor examines the code before actual compilation of code begins
and resolves all these directives before any code is actually generated by
regular statements.
• can extend through more than one line is by preceding the newline
character at the end of the line by a backslash (\).
45
Contd.
• e.g.,
46
Contd…
• Output:
47
Contd…
• The #include directive:
– When the preprocessor finds an # include directive it replaces the header
by the entire content of the specified header file or file.
48
Scope Resolution operator(::)
49
Contd..
• E.g.,
50
Namespace
• Namespaces allow to group entities like classes, objects and functions under a
name.
• In this way the global scope can be divided in "sub-scopes", each one with its
own name.
• The purpose of namespace is to localize a name of identifiers to get rid of
naming conflicts across different modules designed by different members of
programming team.
• Syntax for defining Namespace:
– namespace namespace_name
{
entities; // declaration of variables, functions, classes, etc
}
51
Contd..
• For example:
– namespace myNamespace
– myNamespace::a
– myNamespace::b
52
Contd..
• Example1:
53
Contd..
• Repeated use of variable in the name space
54
Contd..
• Repetitive use of namespace name can be eliminated by including the
namespace in the source file as:
– Syntax: using namespace namespace_name;
– Example:
55
Contd..
• Including the specific component from the name space as:
– Syntax: Using namespace_name::component_name
– Example:
56
Note the following fact about the namespace:
• We can define namespace with the same namespace name which has already
been used.
– namespace outer
{ entities;
namespace inner
entities;
}}
58
Input/ Output stream(cin and cout)
• C++ uses a convenient abstraction called streams (a flow of data)
to perform input and output operations in sequential media such
as the screen, the keyboard or a file.
– cout
– cin
59
Contd..
• The output with cout:
– The << operator inserts the data that follows it into the stream
object that precedes it.
61
Contd…
• Output:
62
Contd..
• Cascading of insertion operator(<<):
– Multiple insertion operations (<<) can be chained in a single
statement to direct a series of output stream to the cout
object.
63
Contd..
• E.g.,
64
Contd..
• Output:
65
Contd..
• Input with cin:
– In most program environments, the standard input by default is the
keyboard, and the C++ stream object defined to access it is cin.
– For formatted input operations, cin is used together with the extraction
operator(>>).
– This operator is then followed by the variable where the extracted data is
stored.
– The >> operator extracts the value from the stream object cin in its left and
place to the variable on its right.
– For example: In the statement cin>> a; The >> operator extracts the value
from cin object that is entered form the keyboard and assigns it to the
variable a.
66
Contd..
• E.g.,
67
Contd..
• Output:
68
Contd..
• Cascading of extraction (>>) operator:
– The streams are extracted and values are assigned form left to right.
69
Contd..
• E.g.,:
70
Contd..
• Output:
71
Contd..
• Example Program: to convert temperature in Fahrenheit to
celsius
72
Contd..
• Output:
73
Manipulators
• Manipulators are operators used in C++ for formatting output.
The data is manipulated by the programmer’s choice of display.
• There are numerous manipulators available in C++. Some of the
more commonly used manipulators are:
– endl
– setw
74
Contd..
• The endl manipulator:
– It has same effect as using the newline character ‘\n’.
75
Contd..
• Program:
76
Contd..
• Output:
77
Contd..
• The setw manipulator:
– If we do not use setw, the output is left justified by default and it occupies
78
Control statements
• Not many programs execute all their statements in strict order from
beginning to end.
• The flow of control jumps from one part of the program to another,
depending on calculations performed in the program.
• Program statements that cause such jumps are called control statements.
– decisions/selection/branching statements
– Jumps statements
79
Decisions(Selection structures)
• This structures makes one-time decision, causing a one-
time jump to a different part of the program, depending
on the value of an expression.
80
Contd..
• The if statements:
– Syntax:
if (testExpression)
// statements
81
Contd..
• How if statement works?
82
Contd..
• Example Program:
output1
output2
83
Contd..
• The if...else statements:
– Syntax:
• If(testExpression)
//statements
else
//statements
84
Contd..
• How if...else statement works?
85
Contd..
• Example program:
86
Contd..
• The Nested if…else statements:
• Syntax:
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true
}
..
else
{
// statements to be executed if all test expressions are false
} 87
Contd..
• Example program:
88
Contd..
• The switch statements: When a case constant is found that
matches the switch expression, control of the program passes to
the block of code associated with that case.
– Syntax:
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
...
default:
// code to be executed if n doesn't match any constant
}
89
Contd..
• How switch statements works?
90
Contd..
• Example:
91
Contd..
• Output:
92
Loops(Iteration statements)
• Loops cause a section of your program to be repeated a certain
number of times. The repetition continues while a condition is
true. When the condition becomes false, the loop ends and
control passes to the statements following the loop.
– Do…while loop
93
Contd..
• The For loops:
– Syntax:
// codes
94
Contd..
• How for loops works?
95
Contd..
• Example program:
96
Contd..
• The while loop:
– Syntax:
while (testExpression)
// codes
97
Contd..
• How while loop works?
98
Contd..
• Example program:
99
Contd..
• The do…while loop:
– The do...while loop is a variant of the while loop with one important
difference. The body of do...while loop is executed once before the test
expression is checked.
– The syntax of do..while loop is:
do
// codes;
} while (testExpression);
100
Contd..
• How do...while loop works?
101
Contd..
• Example program:
102
Contd..
• Output:
103
Jump statements
104
Contd..
• The break statement:
105
Contd..
• E.g.,:
106
Contd..
• The Continue statements:
following iteration.
107
Contd..
• E.g.,
108
Contd..
• Example2:
109
Contd..
• Output:
110
Contd..
• The goto statement:
111
Contd..
• Example:
112
Contd..
• Output:
113
Contd..
• The return statement:
– It is used to transfer the program control back to the caller of
the method.
114
Functions
• In programming, function refers to a segment that groups code to
perform a specific task.
– Library Function
– User-defined Function
115
User-defined Function
• C++ allows programmer to define their own function.
• A user-defined function groups code to perform a specific task and that group
• When the function is invoked from any part of program, it all executes the
116
Contd..
• How C++ functions works?
117
Contd..
• For Example:
118
Default Argument
• When declaring a function we can specify a default value for each of
• If a value for that parameter is not passed when the function is called,
the default value is used, but if a value is specified this default value is
119
Contd..
• For Example:
Output:
120
Inline Function
• We make a function if the same operation is to be repeated at different
location of the program.
• Functions save the memory space as all the calls to the function cause
the same code to be executed.
121
Contd..
• If a function is inline, the compiler places a copy of the code of that function
at each point where the function is called at compile time.
• The compiler can ignore the inline qualifier in case defined function is more
complex(e.g., contains loop).
• To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function.
// body of function
122
Contd..
• For example 1:
Output:
123
Contd..
• Example 2: Inline function
124
Contd..
• Advantages of inline function:
macros.
125
Contd..
• Disadvantages of inline function:
– If the function call is made repeatedly, object code size increases and thus
requires more memory at the time of execution.
– The compiler can not perform inlining if the function is too complicated.
126
Function overloading
• Function Overloading is a mechanism that allows a single
functions.
– E.g.,:
• display(int)
• display(float)
127
Contd..
• Functions can be overloaded in two ways:
– Function overloading with different types of arguments
128
Contd..
• Function overloading with different types of arguments:
• When we need to have same operation on different types of
variables, we overload the functions with different type of
arguments.
129
Contd..
• For Example:
130
Contd..
• Function overloading with different number of arguments
– As in type of argument, overloading can be done with the number
of arguments.
131
Contd..
• For example:
132
Contd..
• Output:
133
Passing arguments to the function
• Three ways to pass arguments to the function (Types of function
call):
– Pass by value
– Pass by reference
– Pass by pointer
134
Contd..
• Pass by value: Copies of the arguments are passed of the function not the
variables themselves.
• Example:
135
Contd..
• Pass By reference: In case of pass by reference, address of the
variable(i.e., variable itself) not copies of the arguments are passed to the
function.
• Example:
136
Contd..
• Pass by pointer:
reference.
137
Contd..
• Example:
138
Returning form Function
• Three way to return value form one function to another function.
– Return by value
– Return by reference
– Return by pointer
139
Contd..
• Return By value: When a value is returned a copy of that value is returned to
the caller form the called function.
140
Contd..
• Return by reference: when a variable is returned by reference, a
reference to the variable is passed back to the caller.
• Example:
141
Contd..
• Return By pointer: Returns the address of the variable.
• Example:
142
Scope/Visibility and Storage class
• Scope (Visibility):
– scope of a variable determines which part of the program
can access it.
• Class scope
143
Contd..
• Local Scope: A variable declared within a block of code
enclosed by braces({ }) is accessible only within that block, and
only after the point of declaration. Outside that they are
unavailable.
• Global scope: Any variable declared outside all blocks has global
scope. It is accessible anywhere in the file after its declaration.
145
Contd..
• Output:
146
Contd..
• Storage Class:
– Every variable has two features: type and storage class.
• External
• Static
• Register
• Mutable
148
Contd..
• Automatic Storage Class:
– The keyword auto is used to declare automatic variables(or local
variables).
• Syntax: auto int var;
149
Contd..
• Example:
150
Contd..
• Output:
151
Contd..
• Example: scope and life of global variable is entire program
152
Contd..
• Output:
153
Contd..
– The extern modifier is most commonly used when there are two or more
– When you have multiple files and you define a global variable , which will
be used in other files also, then extern will be used in another file to give
154
Contd..
• Example: Mul.cpp file to illustrate external storage class
155
Contd..
• Example: Mul.cpp file to illustrate external storage class
156
Contd..
• Output:
157
Contd..
• Static storage class:
– Keyword static is used for specifying a static variable.
– For example:
int main()
{
static float a;
... .. ...
}
– A static local variable exists only inside a function where it is declared
(similar to a local variable) but its lifetime starts when the function is called
and ends only when the program ends.
– The main difference between local variable and static variable is that, the
value of static variable persists the end of the program.
158
Contd..
• Example:
159
Contd..
• Output:
160
Contd..
• Register storage class:
– Keyword register is used for specifying register variables.
• Syntax: register datatype var_name1 [= value];
– However, this keyword was deprecated in C++11 and should not be used.
161
Contd..
• Mutable storage class:
162
Pointers
• A pointer is a variable whose value is the address of another
variable.
– Pointers enable to build complex linked data structures like linked lists
trees , etc.
163
Contd..
• Pointer variables declaration:
– Like any variable, you must declare a pointer before you can work
with it.
– Where,
• type is the data type pointed to by the pointer. This type is not the type of
the pointer itself, but the type of the data the pointer points to.
• asterisk (*) used when declaring a pointer only means that it is a pointer
164
Contd..
• For Example:
– int *ip; // pointer to an integer
– The actual data type of the value of all pointers, whether integer, float,
character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that the
pointer points to.
165
Contd..
variable
166
Contd..
• Pointer initialization:
– Pointers can be initialized either to the address of a variable , or to the
value of another pointer(or array):
– Pointer initialization to the address of a variable:
• For example:
int myvar;
int * myptr = &myvar;
– Pointer initialization to the value of another pointer:
• For example:
int myvar;
int *f = &myvar;
int *bar = f;
–
167
Contd..
• Operators in Pointers:
– Reference operator (&)/address-of and
168
Contd..
• Reference operator (&)/address-of and:
– The address of a variable can be obtained by preceding the
name of a variable with an ampersand sign (&), known
as address-of operator.
– For example: int a =10;
int *p = &a; //pointer declaration and initialization
int b = a; // value of a is assigned to b so, b = 10
– This would assign the address of variable a to pointer variable
p, we are no longer assigning the content of the variable itself
to p, but its address..
169
Contd..
• Dereference operator (*):
– An interesting property of pointers is that they can be used to access the
variable they point to directly. This is done by preceding the pointer name
with the dereference operator (*). The operator itself can be read as "value
pointed to by".
– This could read as x equal to value pointed by p, and the statement would
actually assign the value of 10 to x
170
Contd..
• Example1:
171
Contd..
• Output:
172
Contd..
• Example2:
173
Contd..
• Output:
174
Contd..
• Pointers and Arrays:
– The concept of arrays is related to that of pointers. In fact, arrays
work very much like pointers to their first elements, and, actually,
an array can always be implicitly converted to the pointer of the
proper type.
• int x[20];
• int* p;
• p =x;
175
Contd..
• After that, p and x would be equivalent and would have very
similar properties.
176
Contd..
• Example:
177
Contd..
• Output:
• Note: Pointers and arrays support the same set of operations, with the same
meaning for both. The main difference being that pointers can be assigned
new addresses, while arrays cannot.
178
Contd..
• Passing Array to a Function in C++:
179
Contd..
• Way-1 :Formal parameters as a pointer as follows −
void myFunction(int *param)
{
………
……..
….. . .
}
180
Contd..
...
…..
…….
181
Contd..
• Way-3: Formal parameters as an unsized array as follows :
{
...
…..
…..
}
182
Contd..
• Example1:
183
Contd..
• Output:
184
Contd..
• Example2:
185
Contd..
• Output:
186
Contd..
• Example3:
187
Contd..
• Output:
188
Contd..
• Example: passing 2-D Array to function
189
Contd..
• Output:
190
Dynamic Memory Allocation with new and delete
• Arrays can be used to store multiple homogenous data but there are serious
drawbacks of using arrays.
• You should allocate the memory of an array when you declare it but most of
the time, the exact memory needed cannot be determined until runtime.
• The downside to this is unused memory is wasted and cannot be used by any
other programs.
191
Contd..
• Operators new and new[]
– Dynamic memory is allocated using operator new.
192
Contd..
– Its syntax is:
pointer = new type
pointer = new type [number_of_elements]
193
Contd..
– For example:
int * p;
194
Contd..
• Operators delete and delete[]
• In most cases, memory allocated dynamically is only needed during specific
periods of time within a program; once it is no longer needed, it can be freed
so that the memory becomes available again for other requests of dynamic
memory. This is the purpose of operator delete, whose syntax is:
delete pointer;
delete[] pointer;
195
Contd..
• Example:
196
Contd..
• Output
197
Thank You !
198