0% found this document useful (0 votes)
13 views59 pages

C++

C++ is a cross-platform, high-performance programming language developed as an extension of C, featuring object-oriented capabilities and control over system resources. It has undergone several updates, with the latest being C++23, and is widely used in various applications including operating systems and GUIs. The document provides an introduction to C++ syntax, variables, user input, and basic operators, along with examples to help beginners get started.

Uploaded by

Ali Muzzammil
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)
13 views59 pages

C++

C++ is a cross-platform, high-performance programming language developed as an extension of C, featuring object-oriented capabilities and control over system resources. It has undergone several updates, with the latest being C++23, and is widely used in various applications including operating systems and GUIs. The document provides an introduction to C++ syntax, variables, user input, and basic operators, along with examples to help beginners get started.

Uploaded by

Ali Muzzammil
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/ 59

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 5 major times in 2011, 2014, 2017, 2020, and 2023 to C++11, C++14, C++17, C++20,

and C++23.

Why Use C++


C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.

C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be

reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to multiple platforms.

C++ is fun and easy to learn!

As C++ is close to C , C# and Java , it makes it easy for programmers to switch to C++ or vice versa.

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++ supports classes and objects, while C does not.

Muzzamil Arain 1
C++ Get Started
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

There are many text editors and compilers to choose from. In this tutorial, we will use an IDE (see below).

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.

We will use Code::Blocks in our tutorial, which we believe is a good place to start.

You can find the latest version of Codeblocks at http://www.codeblocks.org/ . Download the mingw-setup.exe file,
which will install the text editor with a compiler.

Muzzamil Arain 2
C++ Quickstart
Let's 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 ):

myfirstprogram.cpp
#include <iostream>

using namespace std;

int main() {

cout << "Hello World!";

return 0;

Muzzamil Arain 3
C++ Syntax
Let's break up the following code to understand it better:

Example
#include <iostream>

using namespace std;

int main() {

cout << "Hello World!";

return 0;

Example explained
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.

Don't worry if you don't understand how #include <iostream> and using namespace std works. Just think
of it as something that (almost) always appears in your program.

Muzzamil Arain 4
C++ Syntax
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: C++ is case-sensitive: "cout" and "Cout" has different meaning.

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.

Muzzamil Arain 5
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:

Example
#include <iostream>

int main() {

std:: cout << "Hello World!";

return 0;

It is up to you if you want to include the standard namespace library or not.

Muzzamil Arain 6
C++ Statements
A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements .

The following statement "instructs" the compiler to print the text "Hello World" to the screen:

Example
cout << "Hello World!";

It is important that you end the statement with a semicolon ;

If you forget the semicolon ( ;), an error will occur and the program will not run:

Muzzamil Arain 7
C++ Output (Print Text)
The cout object, together with the << operator, is used to output values and print text.

Just remember to surround the text with double quotes ( ""):

Example
#include <iostream>

using namespace std;

int main() {

cout << "Hello World!";

return 0;

C++ Print Numbers


You can also use cout() to print numbers.

However, unlike text, we don't put numbers inside double quotes:

Example
#include <iostream>

using namespace std;

int main() {

cout << 3;

return 0;

Muzzamil Arain 8
New Lines
To insert a new line in your output, you can use the \n character:

Example
#include <iostream>

using namespace std;

int main() {

cout << "Hello World! \n ";

cout << "I am learning C++";

return 0;

Muzzamil Arain 9
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
Single-line comments start with two forward slashes ( //).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

Example
// This is a comment

cout << "Hello World!";

Muzzamil Arain 10
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.

C++ Multi-line Comments


Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example
/* The code below will print the words Hello World!

to the screen, and it is amazing */

cout << "Hello World!";

Muzzamil Arain 11
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

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

Declaring (Creating) Variables


To create a variable, specify the type and assign it a value:

Syntax
type variableName = value;

Muzzamil Arain 12
C++ Variables
Example
Create a variable called myNum of type int and assign it the value 15 :

int myNum = 15;

cout << myNum;

You can also declare a variable without assigning the value, and assign the value later:

Example
int myNum;

myNum = 15;

cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example
int myNum = 15; // myNum is 15

myNum = 10; // Now myNum is 10

cout << myNum; // Outputs 10

Muzzamil Arain 13
C++ Variables
Other Types
A demonstration of other data types:

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

Muzzamil Arain 14
Basic Data Types
The data type specifies the size and type of information the variable will store:

DataType Size Description

boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII values

int 2 or 4 bytes Stores whole numbers, without decimals

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

Muzzamil Arain 15
Basic Data Types
The data type specifies the size and type of information the variable will store:

String 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 usage. String values must be surrounded by double quotes:

Example
string greeting = "Hello";

cout << greeting;

To use strings, you must include an additional header file in the source code, the <string> library:

Example
// Include the string library

#include <string>

// Create a string variable

string greeting = "Hello";

// Output string value

cout << greeting;

Muzzamil Arain 16
C++ Variables
Declare Many Variables
To declare more than one variable of the same type , use a comma-separated list:

Example
int x = 5, y = 6, z = 50;

cout << x + y + z;

One Value to Multiple Variables


You can also assign the same value to multiple variables in one line:

Example
int x, y, z;

x = y = z = 50;

cout << x + y + z;

Muzzamil Arain 17
C++ Identifiers
All C++ variables must be identified with unique names .

These unique names are called identifiers .

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and maintainable code:

Example
// Good

int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is

int m = 60;

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

Muzzamil Arain 18
Constants
When you do not want others (or yourself ) to change existing variable values, use the const keyword (this will
declare the variable as "constant", which means unchangeable and read-only ):

Example
const int myNum = 15; // myNum will always be 15

myNum = 10; // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that are unlikely to change:

Example
const int minutesPerHour = 60;

const float PI = 3.14;

Notes On Constants
When you declare a constant variable, it must be assigned with a value:

Example
Like this:

const int minutesPerHour = 60;

Muzzamil Arain 19
C++ User Input
You have already learned that cout is used to output (print) values. Now we will use cin to get user input.

cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).

In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x:

Example
int x;

cout << "Type a number: "; // Type a number and press enter

cin >> x; // Get user input from the keyboard

cout << "Your number is: " << x; // Display the input value

Good To Know
cout is pronounced "see-out". Used for output , and uses the insertion operator ( <<)

cin is pronounced "see-in". Used for input , and uses the extraction operator ( >>)

Muzzamil Arain 20
Creating a Simple Calculator
In this example, the user must input two numbers. Then we print the sum by calculating (adding) the two numbers:

Example
int x, y;

int sum;

cout << "Type a number: ";

cin >> x;

cout << "Type another number: ";

cin >> y;

sum = x + y;

cout << "Sum is: " << sum;

Muzzamil Arain 21
C++ Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int x = 100 + 50;

Although the + operator is often used to add together two values, like in the example above, it can also be used to
add together a variable and a value, or a variable and another variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)

int sum2 = sum1 + 250; // 400 (150 + 250)

int sum3 = sum2 + sum2; // 800 (400 + 400)

C++ divides the operators into the following groups:

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

• Bitwise operators

Muzzamil Arain 22
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x + y

- Subtraction Subtracts one value from another x - y

* Multiplication Multiplies two values x * y

/ Division Divides one value by another x / y

% Modulus Returns the division remainder x % y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Muzzamil Arain 23
Assignment Operators
Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( =) to assign the value 10 to a variable called x :

Example
int x = 10;

The addition assignment operator ( +=) adds a value to a variable:

Example
int x = 10;

x += 5;

Muzzamil Arain 24
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because it

helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are known as

Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator ( >) to find out if 5 is greater than 3:

Example
int x = 5;

int y = 3;

cout << (x > y); // returns 1 (true) because 5 is greater than 3

Muzzamil Arain 25
Comparison Operators
Operatortox <= y Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x > y

< Less than x < y

>= Greater than or equal to x >= y

<= Less than or equal x <= y

Muzzamil Arain 26
Logical Operators
As with comparison operators, you can also test for true ( 1) or false ( 0) values with logical operators .

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Muzzamil Arain 27
C++ Strings
Strings are used for storing text /characters.

For example, "Hello World" is a string.

A string variable contains a collection of characters surrounded by double quotes:

Example
Create a variable of type string and assign it a value:

string greeting = "Hello";

To use strings, you must include an additional header file in the source code, the <string> library:

Example
// Include the string library

#include <string>

// Create a string variable

string greeting = "Hello";

Muzzamil Arain 28
String Concatenation
The + operator can be used between strings to add them together to make a new string. This is called
concatenation :

Example
string firstName = "John ";

string lastName = "Doe";

string fullName = firstName + lastName;

cout << fullName;

Muzzamil Arain 29
Adding Numbers and Strings
WARNING!

C++ uses the + operator for both addition and concatenation .

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example
int x = 10;

int y = 20;

int z = x + y; // z will be 30 (an integer)

If you add two strings, the result will be a string concatenation:

Example
string x = "10";

string y = "20";

string z = x + y; // z will be 1020 (a string)

If you try to add a number to a string, an error occurs:

Example
string x = "10";

int y = 20;

string z = x + y;

Muzzamil Arain 30
String Length
To get the length of a string, use the length() function:

Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

cout << "The length of the txt string is: " << txt.length();

Tip: You might see some C++ programs that use the size() function to get the length of a string. This is just an
alias of length(). It is completely up to you if you want to use length() or size():

Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

cout << "The length of the txt string is: " << txt.size();

Muzzamil Arain 31
C++ Conditions and If Statements
You already know that C++ supports the usual logical conditions from mathematics:

• Less than: a < b

• Less than or equal to: a <= b

• Greater than: a > b

• Greater than or equal to: a >= b

• Equal to a == b

• Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C++ has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is true

• Use else to specify a block of code to be executed, if the same condition is false

• Use else if to specify a new condition to test, if the first condition is false

• Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of C++ code to be executed if a condition is true.

Syntax
if (condition) {

// block of code to be executed if the condition is true

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

Muzzamil Arain 32
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.

Syntax
if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

Example
int time = 20;

if (time < 18) {

cout << "Good day.";

} else {

cout << "Good evening.";

// Outputs "Good evening."

Muzzamil Arain 33
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and condition2 is true

} else {

// block of code to be executed if the condition1 is false and condition2 is false

Example
int time = 22;

if (time < 10) {

cout << "Good morning.";

} else if (time < 20) {

cout << "Good day.";

} else {

cout << "Good evening.";

// Outputs "Good evening."

Muzzamil Arain 34
Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.

It can be used to replace multiple lines of code with a single line, and is often used to replace simple if else

statements:

Syntax
variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:

Example
int time = 20;

if (time < 18) {

cout << "Good day.";

} else {

cout << "Good evening.";

You can simply write:

Example
int time = 20;

string result = (time < 18) ? "Good day." : "Good evening.";

cout << result;

Muzzamil Arain 35
Real Life Example
This example shows how you can use if..else to "open a door" if the user enters the correct code:

Example
int doorCode = 1337;

if (doorCode == 1337) {

cout << "Correct code.\nThe door is now open.\n";

} else {

cout << "Wrong code.\nThe door remains closed.\n";

Muzzamil Arain 36
C++ Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

C++ For Loop


When you know exactly how many times you want to loop through a block of code, use the for loop instead of a
while loop:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {

cout << i << "\n";

Muzzamil Arain 37
C++ While Loop
The while loop loops through a block of code as long as a specified condition is true:

Syntax
while (condition) {

// code block to be executed

In the example below, the code in the loop will run, over and over again, as long as a variable ( i) is less than 5:

Example
int i = 0;

while (i < 5) {

cout << i << "\n";

i++;

Note: Do not forget to increase the variable used in the condition otherwise the loop will never end!

Muzzamil Arain 38
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if
the condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do {

// code block to be executed

while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is
false, because the code block is executed before the condition is tested:

Example
int i = 0;

do {

cout << i << "\n";

i++;

while (i < 5);

Muzzamil Arain 39
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop .

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
// Outer loop

for (int i = 1; i <= 2; ++i) {

cout << "Outer: " << i << "\n"; // Executes 2 times

// Inner loop

for (int j = 1; j <= 3; ++j) {

cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)

Muzzamil Arain 40
C++ Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a
switch statement.

The break statement can also be used to jump out of a loop .

This example jumps out of the loop when i is equal to 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

cout << i << "\n";

Muzzamil Arain 41
C++ Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the
next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

cout << i << "\n";

Muzzamil Arain 42
C++ Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type, specify the name of the array followed by square brackets and

specify the number of elements it should store:

string cars[4];

We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array

literal - place the values in a comma-separated list, inside curly braces:

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

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

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

Muzzamil Arain 43
Access the Elements of an Array
You access an array element by referring to the index number inside square brackets [].

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

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

cout << cars[0];

// Outputs Volvo

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

Change an Array Element


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

cars[0] = "Opel";

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

cars[0] = "Opel";

cout << cars[0];

// Now outputs Opel instead of Volvo

Muzzamil Arain 44
Loop Through an Array
You can loop through the array elements with the for loop.

The following example outputs all elements in the cars array:

Example
// Create an array of strings

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

// Loop through strings

for (int i = 0; i < 5; i++) {

cout << cars[i] << "\n";

This example outputs the index of each element together with its value:

Example
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

for (int i = 0; i < 5; i++) {

cout << i << " = " << cars[i] << "\n";

And this example shows how to loop through an array of integers:

Muzzamil Arain 45
The foreach Loop
There is also a " for-each loop" (introduced in C++ version 11 (2011)), which is used exclusively to loop through

elements in an array (and other data structures, like vectors and lists ):

Syntax
for (type variableName : arrayName) {

// code block to be executed

The following examples output all elements in an array using a " for-each loop":

Example
Loop through integers:

// Create an array of integers

int myNumbers[5] = {10, 20, 30, 40, 50};

// Loop through integers

for (int i : myNumbers) {

cout << i << "\n";

Muzzamil Arain 46
Omit Array Size
In C++, you don't have to specify the size of the array. The compiler is smart enough to determine the size of the

array based on the number of inserted values:

string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements

The example above is equal to:

string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three array elements

However, the last approach is considered as "good practice", because it will reduce the chance of errors in your

program.

Omit Elements on Declaration


It is also possible to declare an array without specifying the elements on declaration, and add them later:

Example
string cars[5];

cars[0] = "Volvo";

cars[1] = "BMW";

cars[2] = "Ford";

cars[3] = "Mazda";

cars[4] = "Tesla";

Note: The example above only works when you have specified the size of the array.

Muzzamil Arain 47
Get the Size of an Array
To get the size of an array, you can use the sizeof() operator:

Example
int myNumbers[5] = {10, 20, 30, 40, 50};

cout << sizeof(myNumbers) ;

Result:

20

Why did the result show 20 instead of 5, when the array contains 5 elements?

It is because the sizeof() operator returns the size of a type in bytes .

To find out how many elements an array has , you have to divide the size of the array by the size of the first element

in the array:

Example
int myNumbers[5] = {10, 20, 30, 40, 50};

int getArrayLength = sizeof(myNumbers) / sizeof(myNumbers[0]) ;

cout << getArrayLength;

Result:

Muzzamil Arain 48
Creating Pointers
You learned from the previous chapter, that we can get the memory address of a variable by using the & operator:

Example
string food = "Pizza"; // A food variable of type string

cout << food; // Outputs the value of food (Pizza)

cout << &food; // Outputs the memory address of food ( 0x6dfed4 )

A pointer however, is a variable that stores the memory address as its value .

A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator.
The address of the variable you're working with is assigned to the pointer:

Example
string food = "Pizza"; // A food variable of type string

string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food

// Output the value of food (Pizza)

cout << food << "\n";

// Output the memory address of food (0x6dfed4)

cout << &food << "\n";

// Output the memory address of food with the pointer (0x6dfed4)

cout << ptr << "\n";

Muzzamil Arain 49
C++ 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.

Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can also create
your own functions to perform certain actions.

To create (often referred to as declare) a function, specify the name of the function, followed by parentheses () :

Syntax
void myFunction() {

// code to be executed

Example Explained
• myFunction() is the name of the function

• void means that the function does not have a return value. You will learn more about return values later in the
next chapter

• inside the function (the body), add code that defines what the function should do

Muzzamil Arain 50
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when

they are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

Example
Inside main, call myFunction():

// Create a function

void myFunction() {

cout << "I just got executed!";

int main() {

myFunction(); // call the function

return 0;

// Outputs "I just got executed!"

Muzzamil Arain 51
A function can be called multiple times:

Example
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!

Muzzamil Arain 52
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 )

Note: If a user-defined function, such as myFunction() is declared after the main() function, an error will occur :

Example
int main() {

myFunction();

return 0;

void myFunction() {

cout << "I just got executed!";

// Error

Muzzamil Arain 53
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:

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:

Example
void myFunction( string fname ) {

cout << fname << " Refsnes\n";

int main() {

myFunction( "Liam" );

myFunction( "Jenny" );

myFunction( "Anja" );

return 0;

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

Muzzamil Arain 54
Function Overloading
With function overloading , multiple functions can have the same name with different parameters:

Example
int myFunction(int x)

float myFunction(float x)

double myFunction(double x, double y)

Consider the following example, which have two functions that add numbers of different type:

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;

Muzzamil Arain 55
C++ What is OOP?
OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform operations on the data, while

object-oriented programming is about creating objects that contain both data and functions.

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

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the

codes that are common for the application, and place them at a single place and reuse them instead of repeating it.

Muzzamil Arain 56
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:

Muzzamil Arain 57
C++ Classes/Objects
C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with its attributes and methods. For example: in

real life, a car is an object . The car has attributes , such as weight and color, and methods , such as drive and brake.

Attributes and methods are basically variables and functions that belongs to the class. These are often referred to

as "class members".

A class is a user-defined data type that we can use in our program, and it works as an object constructor, or a

"blueprint" for creating objects.

Create a Class
To create a class, use the class keyword:

Example
Create a class called " MyClass ":

class MyClass { // The class

public: // Access specifier

int myNum; // Attribute (int variable)

string myString; // Attribute (string variable)

};

Muzzamil Arain 58
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass, so now we can use
this to create objects.

To create an object of MyClass, specify the class name, followed by the object name.

To access the class attributes ( myNum and myString), use the dot syntax (.) on the object:

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

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;

Muzzamil Arain 59

You might also like