0% found this document useful (0 votes)
24 views

Introduction To C++ - Day 1

The document provides an introduction to the C++ programming language, including its history and standards. It discusses basic C++ concepts like variables, types, and comments. It also presents a simple Hello World example program.

Uploaded by

AmmarMahmood
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Introduction To C++ - Day 1

The document provides an introduction to the C++ programming language, including its history and standards. It discusses basic C++ concepts like variables, types, and comments. It also presents a simple Hello World example program.

Uploaded by

AmmarMahmood
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Introduction to the C++ Programming Language

Introduction to the C++ programming language, the C++ Standard Library and
modern C++ standards.

1 Copyright © Slobodan Dmitrovic


Introduction
About this course
This C++ course is an introduction to the C++ programming language, the C++ Standard Library and
modern C++ standards.
About the trainer
Slobodan Dmitrovic is a professional C++ trainer, consultant, and author of a couple of books on C and
C++. Slobodan specializes in C and C++ mentoring, deep technical analysis, and software architecture.
He is an experienced R&D software developer with more than two decades of experience in the
automotive, automation, and telecommunications industries.
C++ history
C++ is a programming language developed by Bjarne Stroustrup in Bell laboratories in the late 70s. The
language started as an extension to the C programming language. In the beginning, it was called "C with
classes" but has since evolved into a completely different programming language.
The first commercial C++ implementation was released in 1985. The first standardized C++
implementation was released in 1998.

2 Copyright © Slobodan Dmitrovic


Introduction
What is C++?
C++ is a programming language. A standardized, general-purpose, multi-paradigm, object-oriented,
systems programming, statically-typed, compiled language.
The C++ Standard Library
C++ implementation is accompanied by a set of useful functions and containers called the C++ Standard
Library.
C++ standards
C++ is governed by the ISO C++ standard. The standard describes the language and serves as a manual
to compiler writers. There are multiple ISO C++ standards, informally named: C++98, C++03, C++11,
C++14, C++17, C++20.
C++ compilers
The C++ compiler is a program that compiles the C++ source code files and turns them into object files.
The linker links the object files and produces an executable file or a library. Some of the C++ compilers
are:
• g++ frontend (as part of the GCC)
• Visual C++ or MSVC (as part of the Visual Studio IDE)
• Clang or clang++ frontend (as part of the LLVM)
3 Copyright © Slobodan Dmitrovic
Compile-time and run-time
Compile-time
The period of time starting with the compilation of our source code and ending with a production of an
executable file or a library. The compilation has many steps, the most important are:
• Preprocessor
• Compilation – production of object files Compilation
• Linkage
Run-time
The period of time starting with the loading or execution of our program or a library and ending with the
termination of our program or a library.

4 Copyright © Slobodan Dmitrovic


Our first program
The function main() is the program's main entry point. An empty main program located inside a text file
arbitrarily named source.cpp looks like:
int main() {}
Main program entry point – function main()
The function main() is the main program entry point. When our program runs, the code inside the main
function gets executed. A function is of type int. The reserved name main is a function name. It is followed
by an empty list of parameters marked by parentheses () and a function body marked with braces {}. The
left brace { marks the beginning of a function body and the right brace marks the ending of a function body.
Braces can also be placed on separate lines:
int main()
{

}
This simple program has no parameters, and no statements inside the function body. It will serve us as a
blueprint, a placeholder for future C++ code.

5 Copyright © Slobodan Dmitrovic


Comments
Comments are used to document the code or be used as notes to other developers. Compiler ignores the
comments. Single line comments in C++ start with a double slash //. We can have one or multiple single-
line comments.
int main() int main()
{ {
// this is a comment // this is a comment
} // this is a second comment
}
Multi-line comments start with the /* and end with the */. They are also known as C-style comments.
int main()
{
/* This is a
multi-line comment */
}

6 Copyright © Slobodan Dmitrovic


Hello World example
The following program is a simple Hello World example. It prints out the Hello World text in a console
window.
#include <iostream>

int main()
{
std::cout << "Hello World.";
}
Explanation
The #include <iostream> preprocessor directive includes the content of the iostream header into our
source file. The iostream header is part of the C++ Standard Library. We need this header to be able to
use the std::cout object, also known as a standard-output stream.
The << operator inserts our Hello World string literal into the output stream. A string literal is enclosed in
double quotes "". The ; character marks the end of the statement. The std name is the standard-library
namespace and the :: symbol is the scope resolution operator. Object cout is part of the std namespace,
and to access it, we need to prepend the call with the std::.

7 Copyright © Slobodan Dmitrovic


Hello World example
We can output multiple string literals using multiple << operators.
#include <iostream>

int main()
{
std::cout << "Some string." << " Another string.";
}
To write to a new line, we need to output a new-line character using the special '\n' literal. Character literals
are enclosed in single quotes.
std::cout << "First line" << '\n' << "Second line.";
Characters can also be part of the string literal.
std::cout << "First line\nSecond line.";
The \ symbol followed by a character represents an escape sequence, a mechanism to output certain
special characters such as the new-line character '\n', single quote character '\'' or a double quote
character '\"'.

8 Copyright © Slobodan Dmitrovic


Types
What is a type?
A type is a property describing a set of possible values and operations on those values. Instances of types
are called objects.
Built-in types
C++ has some built-in types, often referred to as fundamental types. Some of the built-in types are: char,
int, double and bool.
Declaration
A declaration is a statement that introduces a name into a current scope.
int main()
{
char c; // declares a variable, called c, of type char
int x; // declares a variable x of type int
double d; // declares a variable d of type double
bool b; // declares a variable b of type bool
}

9 Copyright © Slobodan Dmitrovic


Types
Initialization
Before being accessed, local variables must be initialized. Accessing an uninitialized variable results in
undefined behavior. We can also use curly braces when initializing.
int main() int main()
{ {
char c = 'A'; char c {'A'};
int x = 123; int x {123};
double d = 456.789; double d {456.789};
bool b = true; bool b {true};
} }
Definition
A declaration followed by initialization is called a definition. Defining a variable is setting a value in memory
for a name.
int main()
{
int x; // declaration
int y = 123; // definition
}
10 Copyright © Slobodan Dmitrovic
char
Type char is used to represent a single character value. Character literals are enclosed in single quotes:
'a', 'C', '\n'.
#include <iostream>

int main()
{
char c = 'A';
std::cout << "The value of c is: " << c;
}
Every character is internally represented by an integer number corresponding to a character using the
character set. We can assign both numeric literals (up to a certain number) and character literals to our
char variable:
char c = 'a';
// is the same as if we had
char c = 97;
// the number 97 in the ASCII table corresponds to a character 'a'

11 Copyright © Slobodan Dmitrovic


int
Type int is used to represent integral numbers, both negative and positive. Integer usually occupies 4
bytes of memory.
#include <iostream>

int main()
{
int x = 123;
std::cout << "The value of x is: " << x << '\n';
int y = -256;
std::cout << "The value of y is: " << y << '\n';
}
Integer literals can be decimal, octal, and hexadecimal. In production, we mainly use the decimal literals.
int main()
{
int a = 10; // decimal literal
int b = 012; // octal literal
int c = 0xA; // hexadecimal literal
}

12 Copyright © Slobodan Dmitrovic


double
Type double is a floating-point type used for storing floating-point values / real numbers with double
precision. The size of type double is usually 8 bytes.
#include <iostream>

int main()
{
double d = 3.14;
std::cout << "The value of d is: " << d;
}
Some of the floating-point literals used for representing double values are:
double x = 213.456;
double y = 1.;
double d = 0.15;
double e = .15;
double f = 3.14e10;
The idiomatic type for representing floating point values in C++ is double. There are other floating-point
types such as float and long double.

13 Copyright © Slobodan Dmitrovic


Type modifiers
Types can have modifiers. Modifiers affect the type's signedness and size.
signed and unsigned
The signed (the default if omitted) modifier means the type can hold both positive and negative values.
The unsigned modifier means the type has unsigned representation, it can only hold zero and positive
values.
int x = 123456;
unsigned y = 4294967295;
short and long
These modifiers affect the type's size. The short modifier means the type will have the width of at least 16
bits. The long type will have the width of at least 32 bits. We can now combine these modifiers together.
#include <iostream>

int main()
{
unsigned long int x = 4294967295;
std::cout << "The value is: " << x;
}

14 Copyright © Slobodan Dmitrovic


Operators
Operators are symbols that perform an operation on their operands and return a result. Operators and
operands make an expression.
Assignment operator =
The assignment operator = assigns a value to a variable / object:
char mychar = 'c'; // define a char variable mychar
mychar = 'd'; // assign a new value to mychar
int x = 123; // define an integer variable x
int y = 789; // define a new integer variable y
y = x; // assign a value of x to y
Arithmetic operators Increment and decrement operators
Arithmetic operators perform arithmetic operations Increment / decrement operators increment /
on their operands. decrement the value of the object by 1.
+ // addition ++a // pre-increment operator
- // subtraction a++ // post-increment operator
* // multiplication --a // pre-decrement operator
/ // division a-- // post-decrement operator
% // modulo

15 Copyright © Slobodan Dmitrovic


Operators
Compound assignment operators Logical operators
Compound assignment operators perform arithmetic Logical operators perform logical operations and
operation and assign a result. return a Boolean value of true or false.
+= // compound addition !a // logical NOT
-= // compound subtraction a && b // logical AND
*= // compound multiplication a || b // logical OR
/= // compound division
%= // compound modulo
Comparison operators Member access operators
Comparison operators compare the operands and Member access operators access the operand's
return a boolean value of true or false. members.
a == b // equal to a.b // member of an object operator
a != b // not equal to a->b // member of a pointer operator
a < b // less than a[b] // subscript operator
a <= b // less than or equal to *a // indirection / dereferencing
a > b // greater than
a >= b // greater than or equal to

16 Copyright © Slobodan Dmitrovic


Standard I/O
Standard input
The standard input stream, the std::cin object and the stream extraction operator >> allow us to accept
data from the standard input / keyboard. They are defined inside the <iostream> header.
#include <iostream>

int main()
{
std::cout << "Please enter a number and press enter: ";
int x = 0;
std::cin >> x;
std::cout << "You entered: " << x;
}
This reads: read from the standard input into our variable x. We can accept multiple values from the
standard input by using multiple >> operators.
int x = 0;
double d = 0.0;
std::cin >> x >> d;

17 Copyright © Slobodan Dmitrovic


Standard I/O
Standard output
The standard output stream, the std::cout object and the stream insertion operator << allow us to output
data to a standard output / console window. They are defined inside the <iostream> header.
#include <iostream>

int main()
{
std::cout << "This is a message for the user." << '\n';
char c = 'A';
std::cout << "The value of c is: " << c;
int x = 123;
std::cout << "The value of x is: " << x;
}
To output multiple values, we separate them using multiple stream insertion operators <<.
char c = 'A';
int x = 123;
std::cout << "The values are: " << c << " and " << x;

18 Copyright © Slobodan Dmitrovic


Arrays
Arrays are sequences of objects of the same type.
int main()
{
int arr[5]; // declare an array of 5 integers
int myarr[5] = { 10, 20, 30, 40, 50 }; // initialize an array of 5 elements
}
We can access individual array elements through a subscript operator [ ] and an index. The first array
element has an index of 0 and the last array element has an index of number_of_elements – 1.
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
arr[0] = 100; // change the value of the first array element
arr[2] = 300; // change the value of the third array element
arr[4] = 500; // change the value of the last array element
}
Once declared, the number of array elements is fixed. We can not insert to nor delete from an array.

19 Copyright © Slobodan Dmitrovic


Arrays
Array elements are positioned sequentially in memory. The following code:
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
}
Can be represented by the following diagram:

20 Copyright © Slobodan Dmitrovic


Pointers
Pointers are types that can hold the address of a particular object. To make the pointer point to an existing
object in memory, we use the address-of operator &.
int main() int main()
{ {
int x = 123; char c = 'A';
int* p = &x; // p points to x char* p = &c; // p points to c
} }
To initialize a pointer that does not point to any object we can use the nullptr literal.
char* p = nullptr; // a null pointer
To access a value stored in an object pointed to by a pointer, we need to dereference a pointer.
Dereferencing is done by prepending a pointer (variable) name with a dereferencing operator *.
char c = 'a';
char* p = &c;
*p = 'b'; // change the value of pointed-to object
std::cout << "The value of the dereferenced pointer is: " << *p;
Pointers are also used in dynamic memory allocation scenarios using operator new and smart pointers.
Prefer smart pointers to raw pointers.

21 Copyright © Slobodan Dmitrovic


Pointers
A pointer pointing at an existing object in memory using the address-of operator:
int x = 123;
int* p = &x; // p points to x
Can be visualized using the following diagram:

22 Copyright © Slobodan Dmitrovic


References
A reference is an alias for an existing object in memory.
type_name& var_name = initializer_var;
Once declared, a reference must be initialized.
int x = 123;
int& y = x; // y is a reference to x
Now, we have two different names referring to the same int object in memory. Changing the value of any of
the variables changes the value of an object in memory. We are using two aliases for the same object.
int x = 123;
int& y = x;
x = 456; // both x and y now hold the value of 456
y = 789; // both x and y now hold the value of 789
A const-reference or a reference to const is a read-only alias to some object. Mainly used as a function
parameter type.
int x = 123;
const int& y = x; // const reference, y is read only

23 Copyright © Slobodan Dmitrovic


References
A reference type is a type whose instances are aliases for an existing object in memory. The code:
int x = 123;
int& y = x; // y is a reference to x
Can be visualized using the following diagram:

24 Copyright © Slobodan Dmitrovic


Automatic type deduction
The auto specifier automatically deduces the object's type based on the type of the initializer.
auto var_name = initializer;
Examples:
auto c = 'a'; // char type
auto x = 123; // int
auto d = 456.789; // double
The type can also be deduced based on the expression's type.
auto d = 123.456 / 789.10; // double
The auto can be used as part of the reference and const-qualified type.
int x = 123;
auto& y = x; // y is of int& type
const auto x = 123; // y is of const int type
We use auto specifier when the type name is:
• hard to deduce
• hard to type manually

25 Copyright © Slobodan Dmitrovic


Statements
Statements are commands, the code that gets executed in some sequence. Most of statements are
expressions ending with a semicolon. The built-in statements are:
Selection statements
Selection statements check the condition and execute other statements based on the condition.
• if statement
• switch statement
Iteration statements
Iteration statements are statements that execute code in a loop. The code in the loop executes 0, 1, or
multiple times, depending on the statement and the condition.
• for statement
• while statement
• do statement
Other statements categories
Other statements categories include:
• expression statements
• block (compound) statements
• declaration statements
• jump statements
26 Copyright © Slobodan Dmitrovic
if statement
The if statement checks the condition, and if the condition is true, it executes the code in the if-branch,
otherwise it executes the code in the else-branch. There are two general syntaxes:
if (condition) statement(s)
if (condition) statement(s) else statement(s)
Example where the statement executes only if the condition is true. For if statements, prefer using the
code blocks, even if there is only one statements inside a branch.
bool b = true; bool b = true;
if (b) std::cout << "Condition true."; if (b) { std::cout << "Condition true."; }
If the condition is true, the if-statement executes, otherwise the else-statement executes.
bool b = false; bool b = false;
if (b) std::cout << "Condition true."; if (b) { std::cout << "Condition true.";
else std::cout << "Condition false."; } else { std::cout << "Condition false."; }
The shorter version is known as a conditional expression.
(condition) ? expression_1 : expression_2
bool mycondition = true;
int x = 0;
int x = (mycondition) ? 10 : 20; // x is now equal to 10
27 Copyright © Slobodan Dmitrovic
switch statement
The switch statement checks the value of the condition and, based on that value, executes the code inside
one of a given set of case labels. If none of the case label statements is equal to the condition, the code
inside the default label is executed.
General syntax: Example:
switch (condition) int x = 2;
{ switch (x)
case value1: {
statement(s); case 1:
break; std::cout << "The value of x is 1.";
case value2: break;
statement(s); case 2:
break; std::cout << "The value of x is 2.";
default: break;
statement(s); default:
break; std::cout << "None of the above.";
} break;
}

28 Copyright © Slobodan Dmitrovic


for statement
The for-statement executes code in a loop. The execution depends on the condition.
for (init_statement; condition; iteration_expression)
{
// statements
}
The for-loop executes the init_statement and the condition first. Following are the statements inside the
for-loop body and finally the iteration_expression is evaluated.
#include <iostream>

int main()
{
for (int i = 0; i < 10; i++)
{
std::cout << "The counter is: " << i << '\n';
}
}

29 Copyright © Slobodan Dmitrovic


while statement
The while-statement executes code while the condition is true. The syntax for the while-loop is:
while (condition)
{
// statements
}
As long as the condition is true, the while-loop executes the code. When the condition becomes false, the
while-loop terminates.
#include <iostream>

int main()
{
int i = 0;
while (i < 10)
{
std::cout << "The value of i is: " << i << '\n';
i++;
}
}

30 Copyright © Slobodan Dmitrovic


do statement
The do-statement is similar to the while-statement, but the condition comes after the body.
do
{
// statements
} while (condition);
The code inside the do-while loop is guaranteed to execute at least once.
#include <iostream>

int main()
{
int i = 0;
do
{
std::cout << "The value of i is: " << i << '\n';
i++;
} while (i < 10);
}

31 Copyright © Slobodan Dmitrovic


Constants
The const type qualifier marks the object as a read-only. We say that our object is now immutable.
const int n = 5;
An object declared const must be initialized.
const int n; // error, no initializer
const int m = 123; // OK
Constants are not modifiable.
const int n = 5;
n++; // error, cannot modify a read-only object
The const modifies an entire type. For example, const int and int are two different types.
constexpr
Another const qualifier is the constant expression named constexpr. It is a constant that can be evaluated
at compile-time. Initializers themselves must be constant expressions.
constexpr int n = 123; // OK
constexpr double d = 456.78; // OK
constexpr double d2 = d; // OK
int x = 123;
constexpr int n2 = x; // error, x is not a constant expression
32 Copyright © Slobodan Dmitrovic
Strings
Type std::string can be used to store and manipulate strings. It is declared inside the <string> header file.
#include <string>

int main()
{
std::string s = "Hello World.";
}
We can add a character, a string literal or another string to our string.
std::string s = "Hello ";
char c = 'W';
s += c; // adding a character
s += "or"; // adding a string literal
std::string s2 = "ld.";
s += s2; // adding another string
Accessing individual characters of a string.
std::string s = "Hello World.";
char c1 = s[0]; // 'H'
char c2 = s.at(0); // 'H';
33 Copyright © Slobodan Dmitrovic
Strings
Comparing two strings using the equality operator. Accepting a string using the std::getline function.
#include <iostream> #include <iostream>
#include <string> #include <string>

int main() int main()


{ {
std::string s1 = "Hello"; std::string s;
std::string s2 = "World."; std::cout << "Enter a string: ";
if (s1 == s2) { std::getline(std::cin, s);
std::cout << "Equal."; std::cout << "You entered: " << s;
} }
}
The string has a member function .c_str() which To create a substring from a string, we use the
returns a pointer to its first elements. .substr() member function.
std::string s = "Hello World."; // a substring starting at the 6th
std::cout << s.c_str(); // position with a length of 5 characters
std::string s = "Hello World.";
std::string mysubstring = s.substr(6, 5);

34 Copyright © Slobodan Dmitrovic


Functions
Functions are reusable pieces of code. They are C++ entities that have a type, a name, a list of optional
parameters and a function body.
type_name function_name(parameters)
{
// statements
// return statement
}
Function declaration – function signature. Function definition – associating a function body
void myFunction(); with the function signature.
int myFunction(); void myFunction() {
int myFunction(int); std::cout << "Hello from a function.";
int myFunction(int x); }
double myFunction(double, double); int numberSqr(int x) {
double myFunction(double x, double y); return x * x;
}
Calling - invoking a function using the function call operator ().
myFunction();
int myresult = numberSqr(10);
35 Copyright © Slobodan Dmitrovic
Functions
The return statement returns the function result to the caller and terminates the function. Functions of non-
void types (except function main) need a return-statement.
int fnSum(int x, int y) { int fnMultiply(int x, int y) {
return x + y; return x * y;
} }
Passing an argument by value.
void myFunction(int byvalue) {
std::cout << "By value: " << byvalue;
}
Passing an argument by reference.
void myFunction(int& byreference) {
byreference++;
std::cout << "By reference: " << byreference;
}
Passing an argument by const reference.
void myFunction(const std::string& byconstreference) {
std::cout << "By const reference: " << byconstreference;
}
36 Copyright © Slobodan Dmitrovic
Functions
We can have multiple functions with the same name but with different parameter types or different
parameters number. This is referred to as function overloading.
void myPrint(char param);
void myPrint(int param);
void myPrint(const std::string& s, double param);
We can implement different function behaviours, depending on the appropriate overload called.
// invoked with myPrint('c');
void myPrint(char param) {
std::cout << "Printing a char: " << param << '\n';
}
// invoked with myPrint(123);
void myPrint(int param) {
std::cout << "Printing an int: " << param << '\n';
}
// invoked for a myPrint("Hello", 123.456);
void myPrint(const std::string& s, double param) {
std::cout << "Printing a string: " << s << " and a double: " << param << '\n';
}

37 Copyright © Slobodan Dmitrovic


Scope
A scope is a part, portion, region of the source code in which a name is valid and can be accessed.
A block-scope is a section of code marked by a block of code starting with { and ending with }.
int main()
{
int x = 123; // the scope of the first x begins here
{
int x = 456; // redefinition of x, the scope of the second x begins here
} // the scope of the second x ends here
// first x resumes here
} // the scope of the first x ends here
Local scope is a scope that starts from the point of declaration till the end of the function block marked
with }.
void myFunction()
{
int x = 123; // the scope of x starts here
} // the scope of x ends here

38 Copyright © Slobodan Dmitrovic


Storage duration
The lifetime of an object is the time an object spends in memory. The lifetime is determined by a so-called
storage duration. Storage duration is a time an object spends in memory.
Automatic storage duration
The automatic storage duration is a duration where memory for an object is automatically allocated at the
beginning of a block and automatically deallocated when the code block ends. A memory for objects with
automatic storage duration is often referred to as automatic store or stack memory.
Dynamic storage duration
The dynamic storage duration is a duration where memory for an object is manually allocated and
manually deallocated during runtime. A memory for objects with dynamic storage duration is often referred
to as free store or heap memory.
Static storage duration
When an object declaration is prepended with a static specifier, it means the storage for a static object is
allocated when the program starts and deallocated when the program ends.

39 Copyright © Slobodan Dmitrovic


Operators new and delete
We can dynamically allocate and deallocate storage for our object and have pointers point to this newly
allocated memory. The operator new allocates space for an object. The allocated memory must be
deallocated using operator delete.
#include <iostream>

int main()
{
int* p = new int;
*p = 123;
std::cout << "The pointed-to value is: " << *p;
delete p;
}
This example allocates space for one integer on the free store. Pointer p now points to this newly allocated
memory. We assign a value to our newly allocated integer object by dereferencing a pointer with *p = 123;.
Finally, we free the memory by calling the operator delete.

40 Copyright © Slobodan Dmitrovic


Operators new and delete
Dynamic memory allocation visualization:
int* p = new int;

41 Copyright © Slobodan Dmitrovic


Operators new and delete
Dynamic memory allocation and dereferencing a pointer visualization:
int* p = new int;
*p = 123;

42 Copyright © Slobodan Dmitrovic


Operators new and delete
Dynamic memory allocation, dereferencing a pointer and deleting a pointer visualization:
int* p = new int;
*p = 123;
delete p;

43 Copyright © Slobodan Dmitrovic

You might also like