0% found this document useful (0 votes)
23 views85 pages

c++ notes

Uploaded by

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

c++ notes

Uploaded by

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

C++ Introduction

 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.
 C++ extension for program file saving is first.cpp .

HISTORY OF C++

 It is a high-level, general-purpose programming


language created by Danish computer scientist Bjarne
Stroustrup..
 First released in 1985 as an extension of the C
programming language.
 C++ has also been found useful in many other contexts,
with key strengths being software infrastructure and
resource-constrained applications, including desktop
applications, video games, servers

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

First program
#include <iostream>
using namespace std;

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

EXAMPLE EXPAIN

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

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:

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:
C++ Output (Print Text)
 The cout object, together with the << operator, is used to
output values/print text:

#include <iostream>
using namespace std;

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

 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 learning C++";
return 0;
}

New Lines
 To insert a new line, 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;
}

 You can also use another << operator and place the \
n character after the text, like this:

EXAMPLE:

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

EXAMPLE:

#include <iostream>
using namespace std;

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

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:

// This is a comment
cout << "Hello World!";

 This example uses a single-line comment at the end of a


line of code:

cout << "Hello World!"; // This is a comment

C++ Multi-line Comments


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

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

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


to the screen, and it is amazing */
cout << "Hello World!";

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
 double - stores floating point numbers, with decimals, such
as 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;

Where type is one of C++ types (such as int),


and variableName is the name of the variable (such
as x or myName). The equal sign is used to assign values to the
variable.

To create a variable that should store a number, look at the


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

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

Other Types
A demonstration of other data types:

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)

Display Variables
The cout object is used together with the << operator to display
variables.

To combine both text and a variable, separate them with


the << operator:

int myAge = 35;


cout << "I am " << myAge << " years old.";

Add Variables Together


To add a variable to another variable, you can use the + operator:

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

Declare Many 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


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

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

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:

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

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):
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable
'myNum'

Notes On Constants
When you declare a constant variable, it must be assigned with a
value:
const int minutesPerHour = 60;

Calculate the Area of a Rectangle


In this real-life example, we create a program to calculate the
area of a rectangle (by multiplying the length and width):

// Create integer variables


int length = 4;
int width = 6;
int area;

// Calculate the area of a rectangle


area = length * width;

// Print the variables


cout << "Length is: " << length << "\n";
cout << "Width is: " << width << "\n";
cout << "Area of the rectangle is: " << area << "\n";

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

Creating a Simple Calculator


In this example, the user must input two numbers. Then we print
the sum by calculating (adding) the two numbers:

int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;

C++ Data Types


As explained in the Variables chapter, a variable in C++ must be
a specified data type:

int myNum = 5; // Integer (whole number)


float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String

Basic Data Types


The data type specifies the size and type of information the
variable will store:

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

Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7
float 4 bytes
Decimal digit

Numeric Types
Use int when you need to store a whole number without
decimals, like 35 or 1000, and float or double when you need a
floating point number (with decimals), like 9.99 or 3.14515.

int

int myNum = 1000;


cout << myNum;

float

float myNum = 5.75;


cout << myNum;

double

double myNum = 19.99;


cout << myNum;

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 or seven decimal digits, while double variables
have a precision of about 15 digits. Therefore it is safer to
use double for most calculations.

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;

Boolean 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 Coding is Fun = true;


bool cake is Tasty = false;
cout << Coding is Fun; // Outputs 1 (true)
cout << cake is Tasty; // Outputs 0 (false)

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

Alternatively, if you are familiar with ASCII, you can use ASCII
values to display certain characters:

char a = 65, b = 66, c = 67;


cout << a;
cout << b;
cout << c;

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:

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

// Output string value


cout << greeting;

Using Different Data types:-

// Create variables of different data types


int items = 50;
double cost_per_item = 9.99;
double total_cost = items * cost_per_item;
char currency = '$';

// Print variables
cout << "Number of items: " << items << "\n";
cout << "Cost per item: " << cost_per_item << "" << currency
<< "\n";
cout << "Total cost = " << total_cost << "" << currency << "\n";

Operators:-
Operators are used to perform operations on variables and values.

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


values:

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:

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

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

* Multiplicatio Multiplies two values x*y


n
/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

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


1

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


1

2. 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:

int x = 10;

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


variable:

int x = 10;
x += 5;

A list of all assignment operators:

Operator Example Same As

= x=5 x=5
+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

3. 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:

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

A list of all comparison operators:

Operator 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 to x <= y


4. 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 Returns true if both statements are true x < 5 && x < 10
and

|| 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 !(x < 5 && x < 10)
true

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:

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:
// Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";

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 = "Kajal ";


string lastName = "Singh";
string fullName = firstName + lastName;
cout << fullName;

In the example above, we added a space after firstName to create


a space between John and Doe on output. However, you could
also add a space with quotes (" " or ' '):

string firstName = "Kajal";


string lastName = "Singh";
string fullName = firstName + " " + lastName;
cout << fullName;

Append
A string in C++ is actually an object, which contain functions
that can perform certain operations on strings. For example, you
can also concatenate strings with the append() function:

string firstName = "Ruchi ";


string lastName = "Singh";
string fullName = firstName.append(lastName);
cout << fullName;

Adding Numbers and Strings


WARNING!
C++ uses the + Operator for both addition and concatenation.
Numbers are added. Strings are concatenated.
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:-
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

//error

(string x = "10";

int y = 20;

string z = x + y;)

String Length
 To get the length of a string, use the length() function:

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


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

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

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


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

Access Strings
You can access the characters in a string by referring to its index
number inside square brackets [].
This example prints the first character in myString:

string myString = "Hello";


cout << myString[0];
// Outputs H

String indexes start with 0: [0] is the first character. [1] is the
second character, etc.

This example prints the second character in myString:

string myString = "Hello";


cout << myString[1];
// Outputs e
To print the last character of a string, you can use the following
code:

string myString = "Hello";


cout << myString[myString.length() - 1];
// Outputs o

Change String Characters


To change the value of a specific character in a string, refer to the
index number, and use single quotes:

string myString = "Hello";


myString[0] = 'J';
cout << myString;
// Outputs Jello instead of Hello

The at() function


The <string> library also has an at() function that can be used to
access characters in a string:

string myString = "Hello";


cout << myString; // Outputs Hello
cout << myString.at(0); // First character
cout << myString.at(1); // Second character
cout << myString.at(myString.length() - 1); // Last character

myString.at(0) = 'J';
cout << myString; // Outputs Jello

User Input Strings


It is possible to use the extraction operator >> on cin to store a
string entered by a user:

string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;

However, cin considers a space (whitespace, tabs, etc) as a


terminating character, which means that it can only store a single
word (even if you type many words):

string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

Omitting Namespace
You might see some C++ programs that run without the standard
namespace library. The using namespace std line can be omitted
and replaced with the std keyword, followed by the :: operator
for string (and cout) objects:

Example:-

#include <iostream>
#include <string>
// using namespace std; - Remove this line

int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}

C-Style Strings
C-style strings are created with the char type instead of string.

The name comes from the C language, which, unlike many other
programming languages, does not have a string type for easily
creating string variables. Instead, you must use the char type and
create an array of characters to make a "string" in C.

As C++ was developed as an extension of C, it continued to


support this way of creating strings in C++:

string greeting1 = "Hello"; // Regular String


char greeting2[] = "Hello"; // C-Style String (an array of
characters)

C++ Math
C++ has many functions that allows you to perform mathematical
tasks on numbers.

Max and min


 The max(x,y) function can be used to find the highest value
of x and y:

cout << max(5, 10);

 And the min(x,y) function can be used to find the lowest


value of x and y:

cout << min(5, 10);


C++ <cmath> Library
Other functions, such as sqrt (square root), round (rounds a
number) and log (natural logarithm), can be found in
the <cmath> header file:

// Include the cmath library


#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);

C++ Booleans
Very often, in programming, you will need a data type that can
only have one of two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE

For this, C++ has a bool data type, which can take the
values true (1) or false (0).

Boolean Values
A boolean variable is declared with the bool keyword and can
take the values true or false:

bool isCodingFun = true;


bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

Boolean Expression
A Boolean expression returns a boolean value, which is
either 1 (true) or 0 (false).
This is useful for building logic and finding answers.

You can use a comparison operator, such as the greater than (>)
operator, to find out if an expression (or variable) is true or false:

int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true),because 10 is higher than 9

Or even easier:

cout << (10 > 9); // returns 1 (true), because 10 is higher than 9

In the examples below, we use the equal to (==) operator to


evaluate an expression:

int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is
equal to 10

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.

if (condition) {
// block of code to be executed if the condition is true
}

In the example below, we test two values to find out if 20 is


greater than 18. If the condition is true, print some text:

if (20 > 18) {


cout << "20 is greater than 18";
}

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

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

C++ Switch Statements


Use the switch statement to select one of many code blocks to be
executed.

Syntax:-
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

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

Example:-

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

The break Keyword


When C++ reaches a break keyword, it breaks out of the switch
block.

This will stop the execution of more code and case testing inside
the block.

When a match is found, and the job is done, it's time for a break.
There is no need for more testing

The default Keyword


The default keyword specifies some code to run if there is no
case match:

Example:-

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

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

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

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

Example:-
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}

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

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

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:

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


if (i == 4) {
continue;
}
cout << i << "\n";
}

Break and Continue in While Loop


You can also use break and continue in while loops:

Break Example:-

int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

Continue example:-

int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}

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

array of four strings

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

array of three integers

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

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

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

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

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

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

Fixed Size (Arrays) vs. Dynamic Size


(Vectors)
You will often hear the terms "fixed size" and "dynamic size"
when discussing arrays in C++.

This is because the size of an array in C++ is fixed, meaning


you cannot add or remove elements after it is created.

Example:-fixed size(arrays)

// An array with 3 elements


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

// Trying to add another element (a fourth element) to the cars


array will result in an error
cars[3] = "Tesla";

Vectors
For operations that require adding and removing array elements,
C++ provides vectors, which are resizable arrays.

The size of a vector is dynamic, meaning it can grow and shrink


as needed.

Vectors are found in the <vector> library, and they come with
many useful functions to add, remove and modify elements:

Example:-dynamic size(vectors)
// A vector with 3 elements
vector<string> cars = {"Volvo", "BMW", "Ford"};

// Adding another element to the vector


cars.push_back("Tesla");

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

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.

You learned from the Data Types chapter that an int type is
usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5
elements) = 20 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;

Loop Through an Array with sizeof()


In the Arrays and Loops Chapter, we wrote the size of the array
in the loop condition (i < 5). This is not ideal, since it will only
work for arrays of a specified size.

However, by using the sizeof() approach from the example


above, we can now make loops that work for arrays of any size,
which is more sustainable.

Instead of writing:

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


for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}

Example:-

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


for (int i = 0; i < sizeof(myNumbers) / sizeof(myNumbers[0]); i+
+) {
cout << myNumbers[i] << "\n";
}

Multi-Dimensional Arrays
A multidimensional array is essentially an array of arrays. This
means that each element of the array is another array, and it can
have more than two dimensions, depending on the requirement.
The most common example is a two-dimensional array, which
can be visualized as a table with rows and columns.

Here is how you can declare and use a multidimensional array in


C++:

1. Declaration of a 2D Array:
int arr[3][4];

This creates an array with 3 rows and 4 columns, meaning


array has 12 elements in total.
2. Initialization of a 2D Array:

You can initialize the array during declaration, as follows:

int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
3. Accessing Elements in a 2D Array:

You can access elements by specifying the indices (row and


column):

int value = arr[1][2];


4. Looping Through a 2D Array:

You typically use nested loops to iterate through a 2D array:

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


for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}

This will print the array elements row by row.

5. 3D Array Example:

A three-dimensional array is like a cube of values. Here's how


you declare and initialize a 3D array

int arr[2][3][4];
you can initialize it
int arr[2][3][4] = {
{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}, {{13, 14, 15, 16},
{17, 18, 19, 20}, {21, 22, 23, 24}}
};
6. Accessing 3D Array Elements:

You access the elements in a 3D array by specifying three indices


(block, row, column):

int value = arr[1][2][3];


7. Looping Through a 3D Array:

Similar to a 2D array, you would use nested loops to iterate


through a 3D array:

#include<iostream>
using namespace std;
int main() {
int arr[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};

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


for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
cout << arr[i][j][k] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}

Example:-

string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

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


for (int j = 0; j < 4; j++) {
cout << letters[i][j] << "\n";
}
}

Example of three dimensional:-

string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};

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


for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
cout << letters[i][j][k] << "\n";
}
}
}

Structures
a structure (struct) is a user-defined data type that allows you to
combine different types of variables under a single name. This is
useful when you need to represent more complex data, like a
group of variables that logically belong together. Structures are
similar to classes, but by default, their members are public
(whereas class members are private by default).

Unlike an array, a structure can contain many different data types


(int, string, bool, etc).

Defining a Structure

Here’s the basic syntax for defining a structure in C++:

struct StructureName {

// Data members

type1 member1;

type2 member2;

// ... more members

};

Defining and Using a Structure

Let's create a structure to represent a Person with a name, age,


and height:

#include <iostream>

using namespace std;

struct Person {
string name;

int age;

float height;

};

int main() {

// Creating a structure variable

Person p1;

// Assigning values to structure members

p1.name = "Sachin Singh";

p1.age = 25;

p1.height = 5.9;

// Accessing structure members

cout << "Name: " << p1.name << endl;

cout << "Age: " << p1.age << endl;

cout << "Height: " << p1.height << endl;

return 0;

Access Structure Members


To access members of a structure, use the dot syntax (.):

Example:-
struct {
int myNum;
string myString;
} myStructure;
myStructure.myNum = 1;
myStructure.myString = "Hello World!";

cout << myStructure.myNum << "\n";


cout << myStructure.myString << "\n";

One Structure in Multiple Variables


You can use a comma (,) to use one structure in many variables:

Example:-

struct {
int myNum;
string myString;
} myStruct1, myStruct2, myStruct3;

Named Structures
By giving a name to the structure, you can treat it as a data type.
This means that you can create variables with this structure
anywhere in the program at any time.

To create a named structure, put the name of the structure right


after the struct keyword:

struct myDataType {
int myNum;
string myString;
};

To declare a variable that uses the structure, use the name of the
structure as the data type of the variable:

myDataType myVar;

Enumeration (Enums)
An enum is a special type that represents a group of
constants (unchangeable values).
To create an enum, use the enum keyword, followed by the name
of the enum, and separate the enum items with a comma:

enum Level {
LOW,
MEDIUM,
HIGH
};

Note that the last item does not need a comma.

It is not required to use uppercase, but often considered as good


practice.

Enum is short for "enumerations", which means "specifically


listed".

 To access the enum, you must create a variable of it.


 Inside the main() method, specify the enum keyword,
followed by the name of the enum (Level) and then the
name of the enum variable (myVar in this example):

enum Level myVar;

Now that you have created an enum variable (myVar), you can
assign a value to it.

The assigned value must be one of the items inside the enum
(LOW, MEDIUM or HIGH):

enum Level myVar = MEDIUM;

By default, the first item (LOW) has the value 0, the second
(MEDIUM) has the value 1, etc.

If you now try to print myVar, it will output 1, which


represents MEDIUM:

#include <iostream>

using namespace std;


int main() {

enum Level { LOW, MEDIUM, HIGH };

Level myVar = MEDIUM;

cout << myVar;

return 0;

Change Values
As you know, the first item of an enum has the value 0. The
second has the value 1, and so on.

To make more sense of the values, you can easily change them:

enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};

int main() {
enum Level myVar = MEDIUM;
cout << myVar; // Now outputs 50
return 0;
}

Enum in a Switch Statement


Enums are often used in switch statements to check for
corresponding values:

enum Level {
LOW = 1,
MEDIUM,
HIGH
};

int main() {
enum Level myVar = MEDIUM;

switch (myVar) {
case 1:
printf("Low Level");
break;
case 2:
printf("Medium level");
break;
case 3:
printf("High level");
break;
}
return 0;
}

Creating References
A reference variable is a "reference" to an existing variable, and
it is created with the & operator:

string food = "Pizza";


string &meal = food;

Now, we can use either the variable name food or the reference
name meal to refer to the food variable:

Example:-

string food = "Pizza";


string &meal = food;

cout << food << "\n";


cout << meal << "\n";

Memory Address
In the example from the previous page, the & operator was used
to create a reference variable. But it can also be used to get the
memory address of a variable; which is the location of where the
variable is stored on the computer.

When a variable is created in C++, a memory address is assigned


to the variable. And when we assign a value to the variable, it is
stored in this memory address.

To access it, use the & operator, and the result will represent
where the variable is stored:

Example:-

string food = "Pizza";

cout << &food;

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


cout << food;

cout << &food;

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";
string* ptr = &food;
cout << food << "\n";

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

cout << ptr << "\n";

Example Explain:-

Create a pointer variable with the name ptr, that points


to a string variable, by using the asterisk sign * (string* ptr).
Note that the type of the pointer has to match the type of the
variable you're working with.

Use the & operator to store the memory address of the variable
called food, and assign it to the pointer.

Now, ptr holds the value of food's memory address.

Get Memory Address and Value


In the example from the previous page, we used the
pointer variable to get the memory address of a variable
(used together with the & reference operator). However,
you can also use the pointer to get the value of the
variable, by using the * operator
(the dereference operator):
Value प्राप्त करना: * ऑपरेटर का उपयोग करके हम
pointer द्वारा point की गई location पर stored value को
प्राप्त कर सकते हैं। इसे dereferencing कहा जाता है।

Example:-

string food = "Pizza";


string* ptr = &food;
cout << ptr << "\n";
cout << *ptr << "\n";
Modify the Pointer Value
You can also change the pointer's value. But note that this will
also change the value of the original variable:

Exampe:-

string food = "Pizza";


string* ptr = &food;

cout << food << "\n";


cout << &food << "\n";
cout << *ptr << "\n";
*ptr = "Hamburger";
cout << *ptr << "\n";
cout << food << "\n";

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

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

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

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

Function Declaration and Definition


A 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)
}

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("Doora");
myFunction("Doremon");
myFunction("lio");
return 0;
}
When a parameter is passed to the function, it is called an
argument. So, from the example above : fname is a parameter,
while Doora , Doremon and lio are arguments.

Default Parameter Value


You can also use a default parameter value, by using the equals
sign (=).

If we call the function without an argument, it uses the default


value ("Norway"):

Example:-

void myFunction(string country = "India") {


cout << country << "\n";
}

int main() {
myFunction("America");
myFunction("Nepal");
myFunction();
myFunction("USA");
return 0;
}

A parameter with a default value, is often known as an


"optional parameter". From the example above, country is an
optional parameter and "India" is the default value

Multiple Parameters
Inside the function, you can add as many parameters as you
want:

Example:-

void myFunction(string fname, int age) {


cout << fname << " Refsnes. " << age << " years
old. \n";
}

int main() {
myFunction("Sachin",23);
myFunction("Kajal", 24);
myFunction("Riya", 22);
return 0;
}

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:

Example:-

int myFunction(int x) {
return 8 + x;
}

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

Example:- function with two parameters

int myFunction(int x, int y) {


return x + y;
}

int main() {
cout << myFunction(11,4);
return 0;
}

Pass By Reference
In the examples from the previous page, we used normal
variables when we passed parameters to a function. You can also
pass a reference to the function. This can be useful when you
need to change the value of the arguments:
Example:-

void swapNums(int &x, int &y) {


int z = x;
x = y;
y = z;
}

int main() {
int firstNum = 60;
int secondNum = 20;

cout << "Before swap: " << "\n";


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

swapNums(firstNum, secondNum);

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


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

return 0;
}

Pass Arrays as Function Parameters


You can also pass arrays to a function:

Example:-

void myFunction(int myNumbers[5]) {


for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}

int main() {
int myNumbers[5] = {50,60,30,40,20};
myFunction(myNumbers);
return 0;
}

Example Explained

The function (myFunction) takes an array as its parameter (int


myNumbers[5]), and loops through the array elements with
the for loop.
When the function is called inside main(), we pass along
the myNumbers array, which outputs the array elements.

Note that when you call the function, you only need to use the
name of the array when passing it as an
argument myFunction(myNumbers). However, the full
declaration of the array is needed in the function parameter (int
myNumbers[5]).

Real Example:-

Fahrenheit to Celsius

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)

Example:- two functions that add numbers of different type:

int FunInt(int a, int b) {


return a + b;
}

double FunDouble(double a, double b) {


return a + b;
}

int main() {
int N1 = FunInt(5, 5);
double N2 = FunDouble(6.5, 8.5);
cout << "Int: " << N1 << "\n";
cout << "Double: " << N2;
return 0;
}
Variable Scope :-
variable scope refers to the region of the program where a
variable can be accessed or used. Understanding the scope of
variables is essential to avoid errors, such as using variables that
are not defined or are out of scope.
variables are only accessible inside the region they are created.
This is called scope.

Types of Variable Scope :-


1. Local Scope:-A variable created inside a function
belongs to the local scope of that function, and can
only be used inside that function:

Example:-
void myFunction() {
int x = 5;
cout << x;
int main() {
myFunction();
return 0;
}

2.Global Scope:- A variable created outside of a function, is


called a global variable and belongs to the global scope.

Global variables are available from within any scope, global and
local.

Example:-

int x = 5;

void myFunction() {
cout << x << "\n";
}

int main() {
myFunction();

cout << x;
return 0;
}

Recursion
Recursion is the technique of making a function call itself. This
technique provides a way to break complicated problems down
into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to


figure out how it works is to experiment with it.

Example:- Adding two numbers together is easy to do, but


adding a range of numbers is more complicated. In the following
example, recursion is used to add a range of numbers together by
breaking it down into the simple task of adding two numbers:

#include <iostream>
using namespace std;

int factorial(int);

int main() {
int n, result;

cout << "Enter a non-negative number: ";


cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}

int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}

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

What are Classes and Objects?


Classes and objects are the two main aspects of object-
oriented programming.

Difference between Classes and Objects :

Classes Objects
Apple

Fruit Mango

A class is a template for objects, and an object is an


instance of a class.
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:-
class MyClass { // The class

public:
int myNum;

string myString;
};

Create an Object
 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:-
class MyClass {
public:
int myNum;
string myString;
};
int main() {
MyClass myObj; // Create an object of
MyClass

myObj.myNum = 15;
myObj.myString = "Some text";

cout << myObj.myNum << "\n";


cout << myObj.myString;
return 0;
}

Multiple Objects
class Car{
public:
string brand;
string model;
int year;
};
int main() {

Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X3";
carObj1.year = 2024;

Car carObj2;
carObj2.brand = "Mahindra";
carObj2.model = "XUV700";
carObj2.year = 2024;

cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
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

Inside Example:-
class MyClass {
public:
void myMethod() { // Method/function
defined inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj;
myObj.myMethod();

return 0;
}

Outside Example:-
class MyClass {
public:
void myMethod();
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj;
myObj.myMethod();
return 0;
}

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

Example:-
class MyClass { //Class name
public:
MyClass() { //Function name //
Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
(this will call the constructor)
return 0;
}

Constructor Parameters
Constructors can also take parameters (just like regular
functions), which can be useful for setting initial values for
attributes.

The following class have brand, model and year attributes, and a
constructor with different parameters. Inside the constructor we
set the attributes equal to the constructor parameters (brand=x,
etc). When we call the constructor (by creating an object of the
class), we pass parameters to the constructor, which will set the
value of the corresponding attributes to the same:

Example:-

class Car {
public:
string brand;
string model;
int year;
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);

cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}

Access Specifiers
By now, you are quite familiar with the public keyword that
appears in all of our class examples:

Example:-

class MyClass {

public: // Access specifier

// class members goes here


};

The public keyword is an access specifier. Access specifiers


define how the members (attributes and methods) of a class can
be accessed. In the example above, the members are public -
which means that they can be accessed and modified from
outside the code.

there are three access specifiers:

 public - members are accessible from outside the class


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

differences between public and private members:

Example:-

class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}

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:

Example:-

#include <iostream>

using namespace std;

class Employee {
private:

int salary;

public:

void setSalary(int s) {

salary = s;

int getSalary() {

return salary;

};

int main() {

Employee myObj;

myObj.setSalary(50000);

cout << myObj.getSalary();

return 0;

Example explained

The salary attribute is private, which have restricted access.

The public setSalary() method takes a parameter (s) and assigns it


to the salary attribute (salary = s).

The public getSalary() method returns the value of the


private salary attribute.
Inside main(), we create an object of the Employee class. Now
we can use the setSalary() method to set the value of the private
attribute to 50000. Then we call the getSalary() method on the
object to return the value.

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

In the example below, the Car class (child) inherits the attributes
and methods from the Vehicle class (parent):

Example:-

#include <iostream>

using namespace std;

class Animal { // Base class

public:

void eat() {

cout << "This animal is eating." << endl;

};

class Dog : public Animal { // Derived class


public:

void bark() {

cout << "The dog is barking." << endl;

};

int main() {

// Create an object of the derived class

Dog myDog;

// Access the member function of the base class

myDog.eat();

// Access the member function of the derived class

myDog.bark();

return 0;

Types of Inheritance:-
1. Single Inheritance

2. Multiple Inheritance

3. Multilevel Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance
1. Single Inheritance

In single inheritance, a class (derived class) inherits from only


one base class. This is the simplest form of inheritance.

Example:-

class Base {

// Base class members

};

class Derived : public Base {

// Derived class members

};

2. Multiple Inheritance

In multiple Inheritance, a class (derived class) inherits from more


than one base class. This allows the derived class to have features
of all the base classes.

Example:-

class Base1 {

// Base class 1 members

};

class Base2 {

// Base class 2 members

};

class Derived : public Base1, public Base2 {

// Derived class members


};

3. Multilevel Inheritance

In multilevel inheritance, a class is derived from another derived


class. This creates a chain of inheritance.

Example:-

class Base {

// Base class members

};

class Intermediate : public Base {

// Intermediate class members

};

class Derived : public Intermediate {

// Derived class members

};

4. Hierarchical Inheritance

In hierarchical inheritance, multiple classes are derived from a


single base class. This allows multiple derived classes to share
the functionality of the base class.

Example:-

class Base {

// Base class members

};
class Derived1 : public Base {

// Derived class 1 members

};

class Derived2 : public Base {

// Derived class 2 members

};

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of


inheritance (for example, combining multiple and hierarchical
inheritance). It often involves complex structures and can lead to
ambiguity, which can be resolved using the virtual keyword (in
case of multiple inheritance).

Example:-

class Base {

// Base class members

};

class Derived1 : public Base {

// Derived class 1 members

};

class Derived2 : public Base {

// Derived class 2 members

};
class Derived3 : public Derived1, public Derived2 {

// Derived class 3 members

};

Summary of Types:

1. Single Inheritance: One base class, one derived class.


2. Multiple Inheritance: One derived class inherits from
multiple base classes.
3. Multilevel Inheritance: A derived class inherits from
another derived class.
4. Hierarchical Inheritance: Multiple derived classes inherit
from a single base class.
5. Hybrid Inheritance: Combination of two or more types of
inheritance.

Access Specifiers
we have only used public (members of a class are accessible from
outside the class) and private (members can only be accessed
within the class). The third specifier, protected, is similar
to private, but it can also be accessed in the inherited class:
Example:-
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}

Polymorphism
Polymorphism means "many forms", and it occurs when we have
many classes that are related to each other by inheritance.
Polymorphism uses those methods to perform different tasks.
This allows us to perform a single action in different ways.
Example:-
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};

Files
The fstream library allows us to work with files.
To use the fstream library, include both the
standard <iostream> AND the <fstream> header file:

Example:-

#include <iostream>
#include <fstream>

There are three classes included in the fstream library, which are
used to create, write or read files:

Class Description

ofstream Creates and writes to files

ifstream Reads from files

fstream A combination of ofstream and


ifstream: creates, reads, and
writes to files

Create and Write To a File


To create a file, use either the ofstream or fstream class, and
specify the name of the file.

To write to the file, use the insertion operator (<<).

Example:-

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

int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";

// Close the file


MyFile.close();
}

You might also like