C++

How to Learn C++ for Beginners

C++ is the widely and most frequently used programming language. This language was established as an improvement of the initially developed C language and influenced by the C language, so it is a superset of the C programming language which also works along with the other tools and libraries that were accessible and were used in the C language. It is a compiled language that is imperious too.

The beginning of the C++ language occurred back in 1983, soon after when ‘Bjare Stroustrup’ worked with classes in the C language inclusively with some additional features like operator overloading. The file extensions used are ‘.c’ and ‘.cpp’. C++ is extensible and not dependent on the platform and includes STL which is the abbreviation of Standard Template Library. So, basically the known C++ language is actually known as a compiled language that has the source file compiled together to form object files, that when combined with a linker produce a runnable program.

On the other hand, if we talk about its level, it is of middle level interpreting the advantage of low-level programming like drivers or kernels and also the higher-level apps like games, GUI, or desktop apps. But the syntax is almost the same for both C and C++.

Components of C++ Language:

#include<iostream>

This command is a header file comprising the ‘cout’ command. There could be more than one header file depending on the needs and preferences of the user.

int main()

This statement is the master program function which is a prerequisite for every C++ program, which means that without this statement one cannot execute any C++ program. Here ‘int’ is the return variable data type telling about the type of data the function is returning.

Declaration:

Variables are declared and names are assigned to them.

Problem statement:

This is essential in a program and could be a ‘while’ loop, ‘for’ loop or any other condition applied.

Operators:

Operators are used in C++ programs and some are crucial because they are applied to the conditions. A few important operators are &&, ||, !, &, !=, |, &=, |=, ^, ^=.

C++ Input Output:

Now, we will discuss the input and output capabilities in C++. All of the standard libraries used in C++ are providing maximum input and output capabilities that are performed in the form of a sequence of bytes or are normally related to the streams.

Input stream:

In case the bytes are streamed from the device to the main memory, it is the input stream.

Output stream:

If the bytes are streamed in the opposite direction, it is the output stream.

A header file is used to facilitate input and output in C++. It is written as <iomanip> which provides methods for example stew and set precision. The input and output commands are cin, cout, cerr, and clog. Here, ‘cin’ denotes the standard input and ‘cout’ signifies the standard output device used with the stream insertion operators (<<) to display statements on the screen.

Example:

We will be displaying a string message using a character type string.

In the first line, we are including ‘iostream’ which has almost all the essential libraries that we might need for a C++ program’s execution. In the next line, we are declaring a namespace that provides the scope for the identifiers. After calling the main function, we are initializing a character type array that stores the string message and ‘cout’ displays it by concatenating. We are using ‘cout’ for displaying the text on the screen. Also, we took a variable ‘A’ having a character data type array to store a string of characters and then we added both the array message along the static message using the ‘cout’ command.

The output generated is shown below:

Example:

In this case, we would represent the age of the user in a simple string message.

In the first step we are including the library. After that, we are using a namespace that would provide the scope for the identifiers. In the next step, we are calling the main() function. After which, we are initializing age as an ‘int’ variable. We are using the ‘cin’ command for input and the ‘cout’ command for output of the simple string message. The ‘cin’ inputs the value of age from the user and the ‘cout’ displays it in the other static message.

This message is shown on the screen after executing the program so the user can get age and then press ENTER.

Example:

Here, we demonstrate how to print a string by the use of ‘cout’.

To print a string, we initially include a library and then the namespace for identifiers. The main() function is called. Further, we are printing a string output using the ‘cout’ command with the insertion operator that is then displaying the static message on the screen.

C++ Data Types:

Data types in C++ is a very important and widely known topic because it is the basis of C++ programming language. Similarly, any variable used must be of a specified or identified data type.

We know that for all the variables, we use data type while undergoing declaration to limit the data type that needed to be restored. Or, we could say that the data types always tell a variable the kind of data it is storing itself. Every time we define a variable, the compiler allots the memory based on the declared data type as each data type has a different memory storage capacity.

C++ language is assisting the diversity of data types so that the programmer could select the appropriate data type that he might need.

C++ facilitates the usage of the data types stated below:

  1. User-defined data types
  2. Derived data types
  3. Built-in data types

For instance, the following lines are given to illustrate the importance of the data types by initializing a few common data types:

int a = 2; // integer value

float F_N = 3.66; // floating-point value

double D_N = 8.87; // double floating-point value

char Alpha = 'p'; // character

bool b = true; // Boolean

A few common data types: what size they specify and which type of information their variables will store are shown below:

  • Char: With the size of one byte, it will store a single character, letter, number, or ASCII values.
  • Boolean: With the size of 1 byte, it will store and return values as either true or false.
  • Int: With the size of 2 or 4 bytes, it will store whole numbers that are without decimal.
  • Floating point: With the size of 4 bytes, it will store fractional numbers that have one or more decimals. This is adequate for storing up to 7 decimal digits.
  • Double floating point: With the size of 8 bytes, it will also store the fractional numbers that have one or more decimals. This is adequate for storing up to 15 decimal digits.
  • Void: With no specified size a void contains something valueless. Therefore, it is used for the functions that return a null value.
  • Wide character: With a size greater than 8-bit which is usually 2 or 4 bytes long is represented by wchar_t which is similar to char and thus also stores a character value.

The size of the above-mentioned variables may differ depending on the use of the program or the compiler.

Example:

Let’s just write a simple code in C++ that will yield the exact sizes of a few data types described above:

In this code, we are integrating library <iostream>. After which, we are using ‘namespace’. In the next line, we are calling the main() function in which we are utilizing a ‘cout’ command that will print out the sizes of all the data types specified in the program. To find the size of the variables, we have to apply the sizeof() method.

The output is received in bytes as shown in the figure:

Example:

Here we would add the size of two different data types.

First, we are incorporating a header file utilizing a ‘standard namespace’ for identifiers. Next, the main() function is called in which we are initializing the ‘int’ variable at first and then a ‘double’ variable to check the difference between the sizes of these two. Then, their sizes are concatenated by the use of the sizeof() function. The output is displayed by the ‘cout’ statement.

There is one more term that has to be mentioned here and it is ‘Data modifiers’. The name suggests that the ‘data modifiers’ are used along the built-in data types to modify their lengths that a certain data type can uphold by the need or requirement of the compiler.

The following are the data modifiers that are accessible in C++:

  1. Signed
  2. Unsigned
  3. Long
  4. Short

The modified size and also the appropriate range of the built-in data types are mentioned below when they are combined with the data type modifiers:

  • Short int: Having the size of 2 bytes, has a range of modifications from -32,768 to 32,767
  • Unsigned short int: Having the size of 2 bytes, has a range of modifications from 0 to 65,535
  • Unsigned int: Having the size of 4 bytes, has a range of modifications from 0 to 4,294,967,295
  • Int: Having the size of 4 bytes, has a range of modification from -2,147,483,648 to 2,147,483,647
  • Long int: Having the size of 4 bytes, has a range of modification from -2,147,483,648 to 2,147,483,647
  • Unsigned long int: Having the size of 4 bytes, has a range of modifications from 0 to 4,294,967.295
  • Long long int: Having the size of 8 bytes, has a range of modifications from –(2^63) to (2^63)-1
  • Unsigned long long int: Having the size of 8 bytes, has a range of modifications from 0 to 18,446,744,073,709,551,615
  • Signed char: Having the size of 1 byte, has a range of modifications from -128 to 127
  • Unsigned char: Having the size of 1 byte, has a range of modifications from 0 to 255.

C++ Enumeration:

In C++ programming language ‘Enumeration’ is a user-defined datatype. Enumeration is declared as an ‘enum’ in C++. It is used to allot specific names to any constant used in the program. It improves the program’s readability and usability.

Syntax:

We declare enumeration in C++ as follows:

enum enum_Name {Constant1,Constant2,Constant3…}

Advantages of Enumeration in C++:

Enum can be used in the following ways:

  • It can be used frequently in switch case statements.
  • It can use constructors, fields, and methods.
  • It can only extend the ‘enum’ class, not any other class.
  • It can increase compile time.
  • It can be traversed.

Disadvantages of Enumeration in C++:

Enum have also few disadvantages:

If once a name is enumerated it cannot be used again in the same scope.

For Example:

enum Days

{Sat, Sun, Mon};

int Sat=8; // This line has error

Enum cannot be forward declared.

For Example:

enum shapes;

class color

{

void draw (shapes aShape);//shapes have not been declared

};

They look like names but they are integers. So, they can automatically convert to any other datatype.

For Example:

enum shapes

{

Triangle, circle, square

};

int color = blue;

color = square;

Example:

In this example, we see the usage of C++ enumeration:

In this code execution, first of all, we start with #include <iostream>. <iostream> is one of the rich library in C++. It is a built-in library. It involves Input and Output data streams. After this, we use the Standard namespace. Then, we declared ‘enum’ a specific name as Subject and assigned three subjects that are Math, English, and Urdu. Math is assigned value 1. Our goal is to print values of Subject declared in enum. Then, we invoke the main() function. In main() we have cout<<, where ‘c’ means “character” and out means “output”. ‘Cout’ is used to display output. << indicates the insertion operator. By using ‘cout<<’, we print enum values. Next, we will utilize the ‘return 0’ command. This command return the result which is in form of values.

Here is our result of the executed program:

So, as you can see that we have values of Subject: Math, Urdu, English; that is 1,2,3.

Example:

Here is another example through which we clear our concepts about enum:

In this program, we start by integrating the header file <iostream>. It is a built-in library. It involves Input and Output data streams. After this, we have to utilize the Standard namespace. Then, we assigned enum values to the constants that are players. Our target is to display whose over it is. Next, we call our main() function. In the main() function we assigned two constants: Shadab, whose value is 20 to the ‘bowler1’ enum variable; and Afridi, whose value is 25 to the enum variable ‘bowler2’.

We have to use an if-else statement. We have also used the comparison operator inside the ‘if’ statement which means that we are comparing if ‘bowler2’ is greater than ‘bowler1’. Then, the ‘if’ block executes which means it is the over of Afridi. Then, we entered ‘cout<<’ to display the output. First, we print the statement ‘It is over of’. Then, the value of ‘bowler2’. If not, the else block is invoked, which means it is the over of Shadab. Then, by applying the ‘cout<<’ command we display the statement ‘It is over of’. Then, the value of ‘bowler1’.

According to the If-else statement, we have over 25 which is the value of Afridi. It means that the value of the enum variable ‘bowler2’ is greater than ‘bowler1’ that’s why ‘if’ statement is executed.

C++ If else, Switch:

In C ++ programming language, we use the ‘if statement’ and ‘switch statement’ to modify the program’s flow. These statements are utilized to provide multiple sets of commands for the implementation of the program depending on the true value of the mentioned statements respectively. In most cases, we use operators as alternatives to the ‘if’ statement. All of these above-mentioned statements are the selection statements that are known as decisional or conditional statements.

The ‘if’ statement:

This statement is used to test a given condition whenever you feel like changing the flow of any program. Here, if a condition is true the program will execute the written instructions but if the condition is false, it will just terminate. Let’s consider an example;

This is the simple ‘if’ statement used, where we are initializing an ‘int’ variable as 10. Then, a value is taken from the user and it is cross-checked in the ‘if’ statement. If it satisfies the conditions applied in the ‘if’ statement, then the output is displayed.

As the digit chosen was 40, the output is the message.

The ‘If-else’ statement:

In a more complex program where the ‘if’ statement does not usually cooperate, we use the ‘if-else’ statement. In the given case, we are using the ‘if- else’ statement to check the conditions applied.

First, we will declare a variable of datatype ‘int’ named ‘x’ whose value is taken from the user. Now, the ‘if’ statement is utilized where we applied a condition that if the integer value entered by the user is 2. The output will be the desired one and a simple ‘NICE TRY’ message will be displayed. Otherwise, if the entered number is not 2, the output would be different.

When the user writes the number 2, the following output is shown.

When the user writes any other number except 2, the output we get is:

The If-else-if statement:

Nested if-else-if statements are quite complex and are used when there are multiple conditions applied in the same code. Let’s ponder over this using another example:

Here, after integrating the header file and namespace, we initialized a value of variable ‘m’ as 200. The value of ‘m’ is then taken from the user and then cross-checked with the multiple conditions stated in the program.

Here, the user chose value 195. This is why the output shows that this is the actual value of ‘m’.

Switch statement:

A ‘switch’ statement is used in C++ for a variable that needs to be tested if it’s equal to a list of multiple values. In the ‘switch’ statement, we identify conditions in the form of distinct cases and all the cases have a break included at the end of each case statement. Multiple cases are having proper conditions and statements applied to them with break statements that terminate the switch statement and move to a default statement in case no condition is supported.

Keyword ‘break’:

The switch statement contains the keyword ‘break’. It stops the code from executing on the succeeding case. The switch statement’s execution ends when the C++ compiler comes across the ‘break’ keyword and the control moves to the line that follows the switch statement. It’s not necessary to utilize a break statement in a switch. Execution moves on to the next case if it is not used.

In the first line of the code shared, we are including the library. After which, we are adding ‘namespace’. We invoke the main() function. Then, we are declaring a character datatype grade as ‘F’. This grade could be your wish and the result would be shown respectively for the cases chosen. We applied the switch statement for getting the outcome.

If we choose ‘F’ as the grade, the output is ‘better luck next time’ because this is the statement that we want to be printed in case the grade is ‘F’.

Let’s change the grade to X and see what happens. I wrote ‘X’ as the grade and the output received is shown below:

So, the improper case in the ‘switch’ automatically moves the pointer directly to the default statement and terminates the program.

If-else and switch statements have some common features:

  • These statements are utilized to manage how the program is executed.
  • They both evaluate a condition and that determines how the program flows.
  • Despite having different representational styles, they can be used for the same purpose.

If-else and switch statements differ in certain ways:

  • While the user defined the values in ‘switch’ case statements, whereas constraints determine the values in ‘if-else’ statements.
  • It takes time to determine where the change needs to be done, it is challenging to modify ‘if-else’ statements. On the other side, ‘switch’ statements are simple to update because they can be modified easily.
  • To include many expressions, we can utilize numerous ‘if-else’ statements.

C++ Loops:

Now, we’ll discover how to use loops in C++ programming. The control structure known as a ‘loop’ repeats a series of statements. In other words, it is called repetitive structure. All the statements are executed at once in a sequential structure. On the other hand, depending on the specified statement, the condition structure can execute or omit an expression. It may be required to execute a statement more than once in particular situations.

Types of Loop:

There are three categories of loops:

For loop:

Loop is something that repeats itself like a cycle and stops when it doesn’t validate the condition provided. A ‘for’ loop implements a sequence of statements numerous times and condenses the code that copes with the loop variable. This demonstrates how a ‘for’ loop is a specific type of iterative control structure that allows us to create a loop that is repeated a set number of times. The loop would allow us to execute the “N” number of steps by using just a code of one simple line. Let’s talk about the syntax that we will be using for a ‘for’ loop to be executed in your software application.

The syntax of ‘for’ loop execution:

Example:

Here, we use a loop variable to regulate this loop in a ‘for’ loop. The first step would be of assigning a value to this variable we are stating as a loop. After that, we must define whether it is less or greater than the counter value. Now, the body of the loop is to be executed and also the loop variable is updated in case the statement returns true. The above steps are frequently repeated till we reach the exit condition.

  • Initialization Expression: At first, we need to set the loop counter to any initial value in this expression.
  • Test Expression: Now, we need to test the given condition in the given expression. If the criteria are fulfilled, we will carry out the ‘for’ loop’s body and continue updating the expression; if not, we must stop.
  • Update Expression: This expression increases or decreases the loop variable by a certain value after the body of the loop has been executed.

C++ program examples to validate a ‘For’ loop:

Example:

This example shows the printing of integer values from 0 to 10.

In this scenario, we are supposed to print the integers from 0 to 10. First, we initialized a random variable i with a value is given ‘0’ and then the condition parameter we already used checks the condition if i<=10. And when it satisfies the condition and it becomes true, the execution of the ‘for’ loop begins. After the execution, among the two increment or decrement parameters, one shall be executed and in which until the specified condition i<=10 turns into false, the value of the variable i is increased.

No. of Iterations with condition i<10:

No. of

iterations

Variables i<10 Action
First i=0 true 0 is displayed and i is incremented by 1.
Second i=1 true 1 is displayed and i is incremented by 2.
Third i=2 true 2 is displayed and i is incremented by 3.
Fourth i=3 true 3 is displayed and i is incremented by 4.
Fifth i=4 true 4 is displayed and i is incremented by 5.
Sixth i=5 true 5 is displayed and i is incremented by 6.
Seventh i=6 true 6 is displayed and i is incremented by 7.
Eighth i=7 true 7 is displayed and i is incremented by 8
Ninth i=8 true 8 is displayed and i is incremented by 9.
Tenth i=9 true 9 is displayed and i is incremented by 10.
Eleventh i=10 true 10 is displayed and i is incremented by 11.
Twelfth i=11 false The loop is terminated.

Example:

The following instance displays the value of the integer:

In the above case, a variable named ‘a’ is initialized with a value given 50. A condition is applied where the variable ‘a’ is less than 70. Then, the value of ‘a’ is updated such that it is added with 2. The value of ‘a’ is then started from an initial value that was 50 and 2 is added concurrently throughout the loop until the condition returns false and the value of ‘a’ is increased from 70 and the loop terminates.

No. of Iterations:

No. of

Iteration

Variable a=50 Action
First a=50 true The value of a is updated by adding two more integers and 50 becomes 52
Second a=52 true The value of a is updated by adding two more integers and 52 becomes 54
Third a=54 true The value of a is updated by adding two more integers and 54 becomes 56
Fourth a=56 true The value of a is updated by adding two more integers and 56 becomes 58
Fifth a=58 true The value of a is updated by adding two more integers and 58 becomes 60
Sixth a=60 true The value of a is updated by adding two more integers and 60 becomes 62
Seventh a=62 true The value of a is updated by adding two more integers and 62 becomes 64
Eighth a=64 true The value of a is updated by adding two more integers and 64 becomes 66
Ninth a=66 true The value of a is updated by adding two more integers and 66 becomes 68
Tenth a=68 true The value of a is updated by adding two more integers and 68 becomes 70
Eleventh a=70 false The loop is terminated

While Loop:

Until the defined condition is satisfied, one or more statements may be executed. When iteration is unknown in advance, it is very useful. First, the condition is checked and then enters into the body of the loop to execute or implement the statement.

In the first line, we incorporate the header file <iostream> and the standard namespace. We call the main() function. Here, we initialize a variable ‘a’. In the next line, we apply the while condition. Within the while condition, we use the ‘cout’ statement to display the value that is written. Then, we utilize the increment operator to increase the count. In the last line, we utilize the ‘return 0’ statement to end the program.

Do-While Loop:

When the defined condition is satisfied, a series of statements are carried out. First, the loop’s body is carried out. After that, the condition is checked whether it is true or not. Therefore, the statement is executed once. The body of the loop is processed in a ‘Do-while’ loop before evaluating the condition. The program runs whenever the required condition is satisfied. Otherwise, when the condition is false, the program terminates.

Here, we integrate the header file <iostream>. We utilize the main() function in the program. Then, we initialize four integers and use the ‘cin’ statement, so the user can enter the value. In the next line, we initialize two different integers. We apply the ‘do’ statement. Inside the statement, we utilize two arithmetic functions. First, we utilize the multiply operator and second, we utilize the addition operator. Then, we apply the ‘while’ condition in the program outside the ‘do’ statement. Further, we add the ‘cout’ statement to print the result through the ‘result’ integer. In the last line, to terminate the program, we use return 0 commands.

C++ Continue/Break:

C++ Continue Statement:

The continue statement is used in C++ programming language to avoid a current incarnation of a loop as well as move control to the subsequent iteration. During looping, the continue statement can be used to skip certain statements. It is also utilized within the loop in conjunction well with executive statements. If the specific condition is true, all statements following the continue statement are not implemented.

With for loop:

In this instance, we use the ‘for loop’ with the continue statement from C++ to get the required result while passing some specified requirements.

We begin by including the <iostream> library and using ‘namespace std’. Then we are calling the main() function. We utilize for loop. Inside for loop, we declare a variable ‘k’ that is considered to lie between 3 and 8. We make use of a condition to continue the iteration even if (k = = 5). Then used the ‘continue’ statement after specifying the condition. At the end. to show output, we make use of the ‘cout’ command along with the ‘return 0’ command.

With a while loop:

Throughout this demonstration, we used both the ‘while loop’ and the C++ ‘continue’ statement including some conditions to see what sort of output may be generated.

In this example, we set a condition to add numbers to 40 only. If the entered integer is a negative number, then the ‘while’ loop will be terminated. On the other hand, if the number is greater than 40, then that specific number will get skipped from the iteration.

We will include the <iostream> library, utilizing ‘namespace std’ and then call the main() function. We initialize a variable ‘s’. Another variable ‘number’ is declared in the next step. We use the ‘while’ loop. Now, we specify the condition that the required value will be above or equal to zero. To add all positive numbers, we utilize the ‘s += number’ statement. The ‘cout’ command will be applied to show the message on the console ‘Enter any number’. We get the integer from the user by utilizing the ‘cin’ statement. We also employ the ‘if’ statement. Whenever the defined number is greater than 40, the message will be shown. Then, we used the ‘continue’ command. After all these steps, the ‘continue’ statement will be executed. To show the sum of all numbers, we utilize the ‘cout’ statement.

C++ break Statement:

Whenever the break statement is used in a loop in C++, the loop is instantly ended as well as program control restarts at the statement after the loop. It is also possible to end a case inside a ‘switch’ statement.

With for loop:

Here, we will utilize the ‘for’ loop with the ‘break’ statement to observe the output by iterating over different values.

First, we incorporate a <iostream> header file. Next, we utilize ‘namespace std’. After calling the main() function, we used for the loop. Here, we would initialize the variable ‘m’. We will apply the condition that the value of ‘m’ lies between 10 and 20. The ‘break’ condition will be executed as if (m == 17). To print the outcome, we utilized ‘cout’. Then, the ‘return 0’ command will be applied.

With a while loop:

We are going to employ the ‘while’ loop along with the break statement.

We start by importing the <iostream> library. The ‘namespace std’ will be included. Within the main() method, two variables ‘nbr’ and ‘x’ would be initialized. We used the ‘while’ loop and pass ‘true’ as the argument. To get value from the user, we employ the ‘cin’ command. Next, we utilized the ‘if’ statement. Along with this, the ‘break’ condition is applied to specify the condition if (nbr < 0). To add all positive values, we utilized ‘x += nbr’ formulae. To display this sum, we added the ‘cout’ statement.

C++ Functions:

Functions are used to structure an already known program into multiple fragments of codes that execute only when it’s called. In C++ programming language, a function is defined as a group of statements that are given an appropriate name and called out by them. The user can pass data into the functions which we call parameters. Functions are responsible to implement the actions when the code is most likely to be reused.

Creation of a function:

Although C++ delivers many pre-defined functions like main(), which facilitates the execution of the code. In the same way, you can create and define your functions according to your requirement. Just like all the ordinary functions, here, you need a name for your function for a declaration that is added with a parenthesis afterward ‘()’.

Syntax:

Void Labor()

{

// body of the function

}

Void is the return type of the function. Labor is the name given to it and the curly brackets would enclose the body of the function where we add the code for execution.

Calling a function:

The functions that are declared in the code are executed only when they are invoked. For calling a function, you need to specify the name of the function along with the parenthesis which is followed by a semicolon ‘;’.

Example:

Let’s declare and construct a user-defined function in this situation.

Initially, as described in every program, we are assigned a library and namespace for supporting the execution of the program. The user-defined function labor() is always called before writing down the main() function. A function named labor() is declared where a message ‘A labor deserves respect!’ is displayed. In the main() function with the integer return type, we are calling the labor() function.

This is the simple message that was defined in the user-defined function displayed here with the help of the main() function.

Void:

In the aforementioned instance, we noticed that the user-defined function’s return type is void. This indicates that no value is being returned by the function. This represents that the value is not present or is null probably. Because whenever a function is just printing the messages, it does not need any return value.

This void is similarly used in the parameter space of the function to clearly state that this function does not take any actual value while it’s being called. In the above situation, we would also call the labor() function as:

Void labor (void)

{

Cout<< “A labor deserves respect!;

}

The actual parameters:

One can define parameters for the function. The parameters of a function are defined in the argument list of the function that adds to the function’s name. Whenever we call the function, we need to pass the genuine values of the parameters to complete the execution. These are concluded as the Actual parameters. Whereas the parameters which are defined while the function has been defined are known as the Formal Parameters.

Example:

In this example, we are about to exchange or substitute the two integer values through a function.

In the beginning, we are taking in the header file. The user-defined function is the declared and defined named sub(). This function is used for the substitution of the two integer values that are i and n. Next, the arithmetic operators are used for the exchange of these two integers. The value of the first integer ‘i’ is stored in place of the value ‘n’ and the value of n is saved in place of the value of ‘i’. Then, the result after switching the values is printed. If we talk about the main() function, we are taking in the values of the two integers from the user and displayed. In the last step, the user-defined function sub() is called and the two values are interchanged.

In this case of substituting the two numbers, we can see clearly that while using the sub() function, the value of ‘i’ and ‘n’ inside the parameter list are the formal parameters. The actual parameters are the parameter that is passing at the end of the main() function where the substitution function is being called.

C++ Pointers:

Pointer in C++ is quite easier to learn and great to use. In C++ language pointers are used because they make our work easy and all the operations work with great efficiency when pointers are involved. Also, there are a few tasks that won’t be accomplished unless pointers are used like dynamic memory allocation. Talking about pointers, the main idea, that one must grasp is that the pointer is just a variable that will store the exact memory address as its value. The extensive use of pointers in C++ is because for the following reasons:

  • To pass one function to another.
  • To allocate the new objects on the heap.
  • For the iteration of elements in an array

Usually, the ‘&’ (ampersand) operator is used to access the address of any object in the memory.

Pointers and their types:

Pointer has following several types:

  • Null pointers: These are pointers with a value of zero stored in the C++ libraries.
  • Arithmetic pointer: It includes four major arithmetic operators that are accessible which are ++, –, +, -.
  • An array of pointers: They are arrays that are used to store some pointers.
  • Pointer to pointer: It is where a pointer is used over a pointer.

Example:

Ponder over the succeeding example in which the addresses of a few variables are printed.

After including the header file and standard namespace, we are initializing two variables. One is an integer value represented by i’ and another is a character type array ‘I’ with the size of 10 characters. The addresses of both variables are then displayed by using the ‘cout’ command.

The output that we have received is shown below:

This outcome shows the address for both variables.

On the other hand, a pointer is considered a variable whose value itself is the address of a different variable. A pointer always points to a datatype that has the same type which is created with a (*) operator.

Declaration of a pointer:

The pointer is declared in this way:

type *var-name;

The base type of the pointer is indicated by “type,” while the pointer’s name is expressed by “var-name”. And to entitle a variable to the pointer asterisk(*) is used.

Ways of assigning pointers to the variables:

Int *pi; //pointer of an integer datatype

Double *pd; //pointer of a double datatype

Float *pf; //pointer of a float datatype

Char *pc; //pointer of a char datatype

Almost always there is a long hexadecimal number that represents the memory address that is initially the same for all the pointers regardless of their datatypes.

Example:

The following instance would demonstrate how pointers replace the ‘&’ operator and store the address of variables.

We are going to integrate the libraries and directories support. Then, we would invoke the main() function where we first declare and initialize a variable ‘n’ of type ‘int’ with the value 55. In the next line, we are initializing a pointer variable named ‘p1’. After this, we assign the address of the ‘n’ variable to the pointer ‘p1’ and then we show the value of the variable ’n’. The address of ‘n’ that is stored in the ‘p1’ pointer is displayed. Afterward, the value of ‘*p1’ is printed on the screen by utilizing the ‘cout’ command. The output is as follows:

Here, we see that the value of ‘n’ is 55 and the address of ‘n’ that was stored in the pointer ‘p1’ is shown as 0x6ffe14. The value of the pointer variable is found and it is 55 which is the same as the integer variable’s value. Therefore, a pointer stores the address of the variable, and also the * pointer, has the value of the integer stored which will resultantly return the value of the variable initially stored.

Example:

Let’s consider another example where we are using a pointer that stores the address of a string.

In this code, we are adding libraries and namespace first. In the main() function we have to declare a string named ‘makeup’ that has the value ‘Mascara’ in it. A string type pointer ‘*p2’ is used to store the address of the makeup variable. The value of the variable ‘makeup’ is then displayed on the screen utilizing the ‘cout’ statement. After this, the address of variable ‘makeup’ is printed, and in the end, the pointer variable ‘p2’ is displayed showing the memory address of the ‘makeup’ variable with the pointer.

The output received from the above code is as follows:

The first line has the value of the ‘makeup’ variable displayed. The second line shows the address of the variable ‘makeup’. In the last line, the memory address of the ‘makeup’ variable with the usage of the pointer is shown.

C++ Memory Management:

For effective memory management in C++, many operations are helpful for the management of memory while working in C++. When we use C++, the most commonly used memory allocation procedure is dynamic memory allocation where memories are assigned to the variables during runtime; not like other programming languages where the compiler could allocate the memory to the variables. In C++, the deallocation of the variables that were dynamically allocated is necessary, so that the memory is released free when the variable is no longer in use.

For the dynamic allocation and deallocation of the memory in C++, we do the ‘new’ and ‘delete’ operations. It’s critical to manage memory so that no memory is wasted. The allocation of the memory becomes easy and effectual. In any C++ program, the Memory is employed in one of two aspects: either as a heap or a stack.

  • Stack: All the variable which are declared inside the function and every other detail that is interrelated to the function is stored in the stack.
  • Heap: Any sort of unused memory or the portion from where we allocate or assign the dynamic memory during the execution of a program is known as a heap.

While using arrays, the memory allocation is a task where we just cannot determine the memory unless the runtime. So, we assign the maximum memory to the array but this is also not a good practice as in most cases the memory remains unused and it is somehow wasted which is just not a good option or practice for your personal computer. This is why, we have a few operators which are used to allocate memory from the heap during the runtime. The two major operators ‘new’ and ‘delete’ are used for efficient memory allocation and deallocation.

C++ new operator:

The new operator is responsible for the allocation of the memory and is used as follows:

In this code, we include the library <iostream> and namespace. Then, we initialized a pointer with the ‘int’ datatype. In the next line, this pointer is allotted the ‘new’ operator.

Memory has been allocated to the ‘int’ variable successfully with the usage of a pointer.

C++ delete operator:

Whenever we are done using a variable, we must deallocate the memory that we once allocated it because it is no longer in use. For this, we utilize the ‘delete’ operator to release the memory.

The example that we are going to review right now is having both operators included.

We are calculating the average for three different values taken from the user. The pointer variables are assigned with the ‘new’ operator to store the values. The formula of average is implemented. After this, the ‘delete’ operator is utilized which deletes the values that were stored in the pointer variables using the ‘new’ operator. This is the dynamic allocation where allocation is made during the runtime and then the deallocation happens soon after the program terminates.

Use of array for Memory Allocation:

Now, we are going to see how the ‘new’ and ‘delete’ operators are used while utilizing arrays. The dynamic allocation happens in the same way as it happened for the variables as the syntax is almost the same.

In the given instance, we are considering the array of elements whose value is taken from the user. The elements of the array are taken and the pointer variable is declared and then the memory is allocated. Soon after the memory allocation, the array elements’ input procedure is started. Next, the output for the array elements is shown by using a ‘for’ loop. This loop has the iteration condition of elements having a size less than the actual size of the array that is represented by n.

When all the elements are used and there is no further requirement for them to be used again, the memory assigned to the elements will be deallocated using the ‘delete’ operator.

In the output, we could see sets of values printed twice. The first ‘for’ loop was used for writing the down the values for elements and the other ‘for’ loop is used for the printing of the already written values showing that the user has written these values for clarity.

Advantages:

The ‘new’ and ‘delete’ operator is always the priority in C++ programming language and is widely used. When having a thorough discussion and understanding, it is noted that the ‘new’ operator has too many advantages. The advantages of the ‘new’ operator for the allocation of the memory are as follows:

  • The new operator can be overloaded with greater ease.
  • While allotting memory during the runtime, whenever there is not enough memory there would be an automatic exception thrown rather than just the program being terminated.
  • The hustle of using the typecasting procedure is not present here because the ‘new’ operator is having just the same type as the memory which we have allotted.
  • The ‘new’ operator also rejects the idea of using the sizeof() operator as ‘new’ will inevitably calculate the size of the objects.
  • The ‘new’ operator enables us to initialize and declare the objects even though it is generating the space for them spontaneously.

C++ Arrays:

We are going to have a thorough discussion on what arrays are and how they are declared and implemented in a C++ program. The array is a data structure used for storing multiple values in just one variable thus reducing the hustle of declaring many variables independently.

Declaration of arrays:

For declaring an array, one has to first define the type of variable and give an appropriate name to the array which is then added along the square brackets. This will contain the number of elements showing the size of a particular array.

For example:

String makeup[5];

This variable is declared showing that it contains five strings in an array named ‘makeup’. To identify and illustrate the values for this array, we need to use the curly brackets, with each element separately enclosed in double inverted commas, each separated with a single comma in between.

For example:

String makeup[5] = {“Mascara”, “Tint”, “Lipstick”, “Foundation”, “Primer”};

Similarly, if you feel like creating another array with a different datatype supposed to be ‘int’, then the procedure would be the same you just need to change the data type of the variable as shown below:

int Multiples[5] = {2, 4, 6, 8, 10};

While assigning integer values to the array, one must not contain them in the inverted commas, which would only work for the string variable. So, conclusively an array is a collection of interrelated data items with derived data types stored in them.

How do access elements in the array?

All the elements included in the array are assigned with a distinct number which is their index number that is used for accessing an element from the array. The index value starts with a 0 up till one less than the size of the array. The very first value has the index value of 0.

Example:

Consider a very basic and easy example in which we will initialize variables in an array.

In the very first step, we are incorporating the <iostream> header file, which will automatically add all of the necessary libraries in the program. The namespace ‘std’ will provide the scope for directories. In the third line, we are calling the main() function. The curly bracket signifies the starting of the function. After entering into the function, we will declare the ‘int’ type array named ‘digits’. It contains the size of 4, which means it could contain only 4 integer values at once. Each of the elements in the array has been assigned with a unique and different digit separately. The whole array is then displayed with each item being called out individually.

This is the outcome received from the above code. The ‘endl’ keyword moves the other item to the next line automatically.

Example:

In this code, we are using a ‘for’ loop for printing the items of an array.

In the above instance, we are adding the essential library. The standard namespace is being added. The main() function is the function where we are going to perform all the functionalities for the execution of a particular program. Next, we are declaring an int type array named ‘Num’, which has a size of 10. The value of these ten variables is taken from the user with the usage of the ‘for’ loop. For the display of this array, a ‘for’ loop is utilized again. The 10 integers stored in the array are displayed with the help of the ‘cout’ statement.

This is the output we got from the execution of the above code, showing 10 integers having different values.

Example:

In this scenario, we are about to find out the average score of a student and the percentage he has gotten in the class.

First, you need to add a library that will provide initial support to the C++ program. Next, we are specifying the size 5 of the array named ‘Score’. Then, we initialized a variable ‘sum’ of datatype float. The scores of each subject are taken in from the user manually. Then, a ‘for’ loop is used for finding out the average and percentage of all the subjects included. The sum is obtained by using the array and ‘for’ loop. Then, the average is found using the formula of average. After finding out the average, we are passing its value to the percentage which is added to the formula to get the percentage. The average and percentage are then calculated and displayed.

This is the final output where scores are taken in from the user for each subject individually and the average and percentage are calculated respectively.

Advantages of using Arrays:

  • Items in the array are easy to access because of the index number assigned to them.
  • We can easily perform the search operation over an array.
  • In case you want complexities in programming, you can use a 2-dimensional array which also characterizes the matrices.
  • To store multiple values that have a similar datatype, an array could be utilized easily.

Disadvantages of using Arrays:

  • Arrays have a fixed size.
  • Arrays are homogenous which means only a single type of value is stored.
  • Arrays store data in the physical memory individually.
  • The insertion and deletion process is not easy for arrays.

C++ Objects and Classes:

C++ is an object-oriented programming language, which means objects play a vital role in C++. Talking about objects one has to first consider what objects are, so an object is any instance of the class. As C++ is dealing with the concepts of OOP, the major things to be discussed are the objects and the classes. Classes are in fact datatypes that are defined by the user himself and are designated to encapsulate the data members and the functions that are only accessible the instance for the particular class is created. Data members are the variables that are defined inside the class.

Class in other words is an outline or design that is responsible for the definition and declaration of the data members and the functions assigned to those data members. Each of the objects that are declared in the class would be able to share all the characteristics or functions demonstrated by the class.

Suppose there is a class named birds, now initially all the birds could fly and have wings. Therefore, flying is a behavior that these birds adopt and the wings are part of their body or a basic characteristic.

Defining a class:

For defining a class, you need to follow up on the syntax and reset it according to your class. The keyword ‘class’ is used for defining the class and all the other data members and functions are defined inside the curly brackets followed by the class’s definition.

Class NameOfClass

{

Access specifier:

Data members;

Data member functions();

};

Declaring objects:

Soon after defining a class, we need to create the objects to access and define the functions that were specified by the class. For that, we have to write the name of the class and then the name of the object for declaration.

Accessing data members:

The functions and data members are accessed with the help of a simple dot ‘.’ Operator. The public data members are also accessed with this operator but in the case of the private data members, you just cannot directly access them. The access of the data members depends upon the access controls given to them by the access modifiers that are either private, public, or protected. Here’s a scenario that demonstrates how to declare the simple class, data members, and functions.

Example:

In this example, we are going to define a few functions and access the class functions and data members with the help of the objects.

In the first step, we are integrating the library after which we need to include the supporting directories. The class is explicitly defined before calling the main() function. This class is termed ‘vehicle’. The data members were the ‘name of the vehicle and the ‘id’ of that vehicle, which is the plate number for that vehicle having a string, and int datatype respectively. The two functions are declared for these two data members. The id() function displays the id of the vehicle. As the data members of the class are public, so we can also access them outside of the class. Therefore, we are calling the name() function outside of the class and then taking in the value for the ‘VehicleName’ from the user and printing it in the next step. In the main() function, we are declaring an object of the required class which will help in accessing the data members and functions from the class. Further, we are initializing the values for the vehicle’s name and its id, only if the user doesn’t give the value for the vehicle’s name.

This is the output received when the user gives in the name for the vehicle himself and the number plates are the static value assigned to it.

Talking about the definition of the member functions, one must understand that it is not always compulsory to define the function inside of the class. As you can see in the above example, we are defining the function of the class outside the class because the data members are publically declared and this is done with the help of the scope resolution operator shown as ‘::’ along with the name of the class and the function’s name.

C++ Constructors and Destructors:

We are going to have a thorough view of this topic with the help of examples. The deletion and creation of the objects in C++ programming are very important. For that, whenever we create an instance for a class, we automatically call the constructor methods in a few cases.

Constructors:

As the name indicates, a constructor is derived from the word ‘construct’ which specifies the creation of something. So, a constructor is defined as a derived function of the newly created class that shares the class’s name. And it is utilized for the initialization of the objects included in the class. Also, a constructor does not have a return value for itself which means that its return type won’t even be void either. It is not mandatory to accept the arguments, but one can add them if necessary. Constructors are useful in the allocation of memory to the object of a class and in setting the initial value for the member variables. The initial value could be passed in the form of arguments to the constructor function once the object is initialized.

Syntax:

NameOfTheClass()
{
//body of the constructor
}

Types of Constructors:

Parameterized constructor:

As discussed earlier, a constructor does not have any parameter but one can add a parameter of their choice. This will initialize the value of the object while it is being created. To comprehend this concept better, consider the following example:

Example:

In this instance, we would create a constructor of the class and declare parameters.

We are including the header file in the very first step. The next step of using a namespace is supporting directories to the program. A class named ‘digits’ is declared where first, the variables are publically initialized so that they could be accessible throughout the program. A variable named ‘dig1’ with datatype integer is declared. Next, we have declared a constructor whose name is similar to the name of the class. This constructor has an integer variable passed to it as ’n’ and the class variable ‘dig1’ is set equal to n. In the main() function of the program, three objects for the class ‘digits’ are created and assigned some random values. These objects are then utilized to call out the class variables that are assigned with the same values automatically.

The integer values are presented on the screen as output.

Copy constructor:

It is the type of constructor which considers the objects as the arguments and duplicates the values of the data members of one object to the other one. Therefore, these constructors are utilized to declare and initialize one object from the other. This process is called copy initialization.

Example:

In this case, the copy constructor will be declared.

First, we are integrating the library and the directory. A class named ‘New’ is declared in which the integers are initialized as ‘e’ and ‘o’. The constructor is made public where the two variables are assigned the values and these variables are declared in the class. Then, these values are displayed with the help of the main() function with ‘int’ as the return type. The display() function is called and defined afterward where the numbers are displayed on the screen. Inside the main() function, the objects are made and these assigned objects are initialized with random values and then the display() method is utilized.

The output received by the usage of the copy constructor is revealed below.

Destructors:

As the name defines the destructors are used to destroy the created objects by the constructor. Comparable to the constructors, the destructors have the identical name to the class but with an additional tilde (~) followed.

Syntax:

~New()
{
}

The destructor does not take in any arguments and does not even have any return value. The compiler implicitly appeals the exit from the program for clean-up storage that is no longer accessible.

Example:

In this scenario, we are utilizing a destructor for deleting an object.

Here a ‘Shoes’ class is made. A constructor is created that has a similar name as that of the class. In the constructor, a message is displayed where the object is created. After the constructor, the destructor is made which is deleting the objects created with the constructor. In the main() function, a pointer object is created named ‘s’ and a keyword ‘delete’ is utilized to delete this object.

This is the output we received from the program where the destructor is clearing and destroying the object created.

Difference between Constructors and Destructors:

Constructors Destructors
Creates the instance of the class. Destroys the instance of the class.
It has arguments along the class name. It has no arguments or parameters
Called when the object is created. Called when the object is destroyed.
Allocates the memory to objects. Deallocates the memory of objects.
Can be overloaded. Cannot be overloaded.

C++ Inheritance:

Now, we will learn about C++ Inheritance and its Scope.

Inheritance is the method through which a new class is generated or descended from an existing class. The present class is termed as a “base class” or also a “parent class” and the new class that is created is termed as a “derived class”. When we say that a child class is inherited from a parent class it means that the child possesses all the properties of the parent class.

Inheritance refers to an (is a) relationship. We call any relationship an inheritance if ‘is-a’ is used between two classes.

For Example:

  • A parrot is a bird.
  • A Computer is a machine.

Syntax:

In C++ programming, we use or write Inheritance as follows:

class <derived-class>: <access-specifier><base-class>

Modes of C++ Inheritance:

Inheritance involves 3 Modes to inherit classes:

  • Public: In this mode, if a child class is declared then members of a parent class are inherited by the child class as the same in a parent class.
  • Protected: In this mode, the public members the of parent class become protected members in the child class.
  • Private: In this mode, all the members of a parent class become private in the child class.

Types of C++ Inheritance:

Following are the types of C++ inheritance:

1. Single Inheritance:

With this kind of inheritance, classes originated from one base class.

Syntax:

class M
{
Body
};
class N: public M
{
Body
};

2. Multiple Inheritance:

In this sort of inheritance, a class may descend from different base classes.

Syntax:

class M

{

Body

};

class N

{

Body

};

class O: public M, public N

{

Body

};

3. Multilevel Inheritance:

A child class is descended from another child class in this form of inheritance.

Syntax:

class M

{

Body

};

class N: public M

{

Body

};

class O: public N

{

Body

};

4. Hierarchical Inheritance:

Several subclasses are created from one base class in this method of inheritance.

Syntax:

class M

{

Body

} ;

class N: public M

{

Body

} ;

class O: public M

{

} ;

5. Hybrid Inheritance:

In this kind of inheritance, multiple inheritances are combined.

Syntax:

class M

{

  Body

};

class N: public M

{

  Body

};

class O

{

  Body

};

class P: public N, public O

{

  Body

};

Example:

We are going to run the code to demonstrate the concept of Multiple Inheritance in C++ programming.

As we have started with a standard input-output library, then we have given the base class name ‘Bird’ and made it public so that its members can be accessible. Then, we have base class ‘Reptile’ and we also made it public. Then, we have ‘cout’ to print the output. After this, we created a child-class ‘penguin’. In the main() function we have made the object of class penguin ‘p1’. First, the ‘Bird’ class will execute and then the ‘Reptile’ class.

After execution of code in C++, we get the output statements of base classes ‘Bird’ and ‘Reptile’. It means that a class ‘penguin’ is derived from base classes ‘Bird’ and ‘Reptile’ because a penguin is a bird as well as a reptile. It can fly as well as crawl. Hence multiple inheritances proved that one child class can be derived from many base classes.

Example:

Here we will execute a program to show how to utilize Multilevel Inheritance.

We started our program by using input-output Streams. Then, we have declared a parent class ‘M’ which is set to be public. We have called the display() function and ‘cout’ command to display the statement. Next, we have created a child class ‘N’ that is derived from the parent class ‘M’. We have a new child class ‘O’ derived from child class ‘N’ and the body of both derived classes is empty. In the end, we invoke the main() function in which we have to initialize the object of class ‘O’. The display() function of the object is utilized for demonstrating the outcome.

In this figure, we have the outcome of class ‘M’ which is the parent class because we had a display() function in it. So, class ‘N’ is derived from parent class ‘M’ and Class ‘O’ from parent class ‘N’ which refers to the multilevel inheritance.

C++ Polymorphism:

The term ‘Polymorphism’ represents a collection of two words ‘poly’ and ‘morphism’. The word ‘Poly’ represents “many” and ‘morphism’ represents “forms”. Polymorphism means that an object may behave differently in different conditions. It allows a programmer to reuse and extend the code. The same code acts differently according to the condition. The enactment of an object can be employed at run time.

Categories of Polymorphism:

Polymorphism mainly occurs in two methods:

  1. Compile Time Polymorphism
  2. Run Time Polymorphism

Let’s explain.

6. Compile Time Polymorphism:

During this time, the entered program is changed into an executable program. Before the deployment of the code, the errors are detected. There are primarily two categories of it.

  • Function Overloading
  • Operator Overloading

Let’s look at how we utilize these two categories.

7. Function Overloading:

It means a function can perform different tasks. The functions are known as overloaded when there are several functions with a similar name but distinct arguments.

First, we employ the library <iostream> as well as the standard namespace. Then we would declare the user-defined class ‘Add’. Inside the class, we define a function ADD() with two parameters as a public. Again, declare a new function inside the body of the class with the same name but this function has no parameter. Here we initialize three strings. The first two strings have some value and the last string is used to concatenate the first two strings. We utilize the ‘cout’ command to print the result. Next, we call the main() method outside the class. We construct an object of the required class ‘Add’. Now, we call the first function with two parameters and then call the second function as well. In the last step, we include the ‘return 0’ statement to end the program.

Operator Overloading:

The process of defining multiple functionalities of an operator is called operator overloading.

The above example includes the header file <iostream>. Then, we have been utilizing a standard namespace. We define the class ‘Integer’. Within this class, we specify an integer as a class’s private member. Next, we declare Parameterized constructor as a public member and initialize the value of the integer in it. We define a constructor with an overloading prefix operator. Inside this constructor, we perform prefix operation. Moreover, we create a function that displays the increment value by using the ‘cout’ statement. Meanwhile, we invoke the main() function. Here, we create two class objects. The first object passes a value of the integer. Then, utilize the ‘cout’ statement to print the line “Before increment the value is”. Next, we call display() function for first object. The second object uses the pre-increment operator. We use the ‘cout’ command to show the line “After pre-increment the value is”. Then, we use the display() function for the second object.

8. Run Time Polymorphism:

It is the span of time in which the code runs. After the employment of the code, errors can be detected.

Function Overriding:

It happens when a derived class uses a similar function definition as one of the base class member functions.

In the first line, we incorporate the library <iostream> to execute input and output operations. Further, we add the standard namespace. In the next line, we declare a parent class ’Man’. Inside the class, we define a function with two parameters as a public. Then, we use the ‘cout’ statement to display the text “Walking”. Outside the class, we create a child class ‘Animal’ that is derived from the parent class. Here, we create a function having a similar name as the one that was formerly declared in the parent class. Then, utilize the ‘cout’ statement to show the text “Eating”. We use the main() function. Meanwhile, we create a class object ‘m’. Then, we call the function of the parent class as well as the function of the child class. Use the ‘return 0’ command.

C++ Strings:

Now, we’ll discover how to declare and initialize the String in C++. The String is utilized to store a group of characters in the program. It stores alphabetic values, digits, and special type symbols in the program. It reserved characters as an array in the C++ program. Arrays are used to reserve a collection or combination of characters in C++ programming. A special symbol known as a null character is used to terminate the array. It is represented by the escape sequence (\0) and it is used to specify the end of the string.

Get the string using the ‘cin’ command:

It is used to input a string variable without any blank space in it. In the given instance, we implement a C++ program that gets the name of the user using the ‘cin’ command.

In the first step, we utilize the library <iostream>. Meanwhile, we have included the standard namespace. Next, we declare the main() function. We initialize a character type string within the body of the main() function. Then, we use the ‘cout’ statement to print “Enter your name”. We utilize the ‘cin’ command to ask the string from the user. The ‘cout’ command is applied to print the name that would be written by the user. The return 0 statement is added to terminate the program.

The user enters the name “Ahmed Chaudry”. But we get only “Ahmed” as output rather than the complete “Ahmed Chaudry” because the ‘cin’ command cannot store a string with blank space. It only stores the value before space.

Get the string by using the cin.get() function:

The get() function of the cin command is utilized to get the string from the keyboard that may contain blank spaces.

The above example includes the library <iostream> to perform input and output operations. Then, we used a standard namespace. The main() function is called. After that, we initialize a string named ‘s’. In the next step, the ‘cout’ command is utilized to display the statement “Enter a String”. The cin.get() is applied to get the string from the user. By using the cin.get() function we pass a string value and specify the size of the string as a parameter. The ‘cout’ command is utilized again to display the output of the program. In the end, we add the return 0.

A string “My name is Ali” is entered by the user. We get the complete string “My name is Ali” as the outcome because the cin.get() function accepts the strings which contain the blank spaces.

Using 2D (Two-Dimensional) Array of Strings:

In this case, we take input (name of three cities) from the user by utilizing a 2D array of strings.

First, we integrate the header file <iostream> and a standard namespace. We invoke the main() function. Then, we initialize a two-dimensional array of characters with three rows and fifteen columns. In the next step, for loop is used to count the variable ‘i’ to iterate over the required string till the null character is identified. Inside the body of the ‘for’ loop, we utilize the ‘cout’ command to show the line “Enter city name”. Then use the ‘cin’ statement to get the city name. We again utilize another ‘for’ loop and ‘cout’ statement to display the name of cities in a sequence until the loop terminates. Next, the ‘return 0’ command is used.

Here, the user enters the name of three different cities. The program uses a row index to get three string values. Every value is retained in its own row. The first string is stored in the first row and so on. Each string value is displayed in the same way by using the row index.

C++ Standard Library:

The C++ library is a cluster or grouping of many functions, classes, constants, and all the related items enclosed in one proper set almost, always defining and declaring the standardized header files. The implementation of these includes two new header files which are not required by the C++ standard named the <hash_map> and <hash_set>. A long list of mandatory header files is present which is dependent on the requirement of the compiler. The header files contain the header list which has all the content from the C++ Standard Library, inclusively having the specific header files for the Stand Library Template (STL).

The Standard Library removes the hustle of rewriting the instructions while programming. This has many libraries inside it which have stored code for many functions. To make good use of these libraries it is obligatory to link them with the help of header files. When we import the input or output library, this means we are importing all the code that has been stored inside that library and that is how we can use the functions enclosed in it too by hiding all of the underlying code that you might not need to see.

The C++ standard library supports the following two types:

  • A hosted implementation that provisions all of the essential standard library header files described by the C++ ISO standard.
  • A standalone implementation that only requires a portion of the header files from the standard library. The appropriate subset is:
<atomic> (declaring at least

Atomic_signed_lock_free and atomic-unsigned_lock_free)

<cstdint> <ranges>
<bit> <cstdlib>(declaring atleast atexit,abort, at_quick_exit, exit, quick_exit) <ratio>
<cfloat> <exception> <tuple>
<climits> <functional> <typeinfo>
<compare> <initializer_list> <source_location>
<concepts> <iterator> <type_traits>
<coroutine> <limits> <utility>
<cstddef <new>
<cstdarg> <memory> <version>

A few of the header files have been deplored since the past 11 C++ came: That are <ciso646>, <cstdalign>, and <cstdbool>.

The differences between the hosted and freestanding implementations are as illustrated below:

  • In the hosted implementation, we need to use a global function that is the main function. While in a freestanding implementation, the user can declare and define starting and ending functions on its own.
  • A hosting implementation has one thread compulsory running at the matching time. Whereas, in the freestanding implementation, the implementers will themselves decide if they need the concurrent thread’s support in their library.

Types:

Both the freestanding and hosted are supported by C++. The header files are divided into the following two:

  • Iostream parts
  • C++ STL parts (Standard Library)

Whenever we are writing a program for execution in C++, we always call the functions which are implemented inside the STL already. These known functions take in input and display output using identified operators with efficiency.

Considering the history, the STL was initially called the Standard Template Library. Then, the portions of the STL library were then standardized in the Standard Library of C++ that is used nowadays. These include the ISO C++ runtime library and a few fragments from the Boost library inclusive of some other important functionality. Occasionally the STL denotes the containers or more frequently the algorithms of the C++ Standard Library. Now, this STL or Standard Template Library talks entirely about the known C++ Standard Library.

The std namespace and header files:

All of the declarations of functions or variables are done within the standard library with the help of header files that are evenly distributed amongst them. The declaration would not happen unless you don’t include the header files.

Let’s suppose someone is using lists and strings, he needs to add the following header files:

#include <string>

#include <list>

These angular brackets ‘<>’ signifies that one must look up this particular header file in the directory being defined and included. One can also add a ‘.h’ extension to this library which is done if required or desired. If we exclude the ‘.h’ library, we need an addition ‘c’ right before the start of the name of the file, just as an indication that this header file belongs to a C library. For example, you can either write (#include <Cards.h> or #include <cCard>).

Talking about the namespace, the whole C++ standard library lies inside this namespace denoted as std. This is the reason why the standardized library names must be competently defined by the users. For example:

Std::cout << “This shall pass!/n” ;

C++ Vectors:

There are many ways of storing data or values in C++. But for now, we are looking for the easiest and most flexible way of storing the values while writing the programs in the C++ language. So, vectors are containers that are properly sequenced in a series pattern whose size varies at the time of execution depending on the insertion and deduction of the elements. This means that the programmer could change the size of the vector according to his wish during the execution of the program. They resemble the arrays in such a way that they also have communicable storage positions for their included elements. For the checking of the number of values or elements present inside the vectors, we need to use a ‘std::count’ function. Vectors are included in the Standard Template Library of C++ so it has a definite header file that needs to be included first that is:

#include <vector>

Declaration:

The declaration of a vector is shown below.

Std::vector<DT> NameOfVector;

Here, the vector is the keyword used, the DT is showing the data type of the vector which can be replaced with int, float, char, or any other related datatypes. The above declaration can be rewritten as:

Vector<float> Percentage;

The size for the vector is not specified because the size might increase or decrease during execution.

Initialization of Vectors:

For the initialization of the vectors, there is more than one way in C++.

Technique number 1:

Vector<int> v1 = {71, 98, 34, 65};

Vector<int> v2 = {71, 98, 34, 65};

In this procedure, we are directly assigning the values for both of the vectors. The values assigned to both of them are exactly similar.

Technique number 2:

Vector<int> v3(3, 15);

In this initialization process, 3 is dictating the size of the vector and 15 is the data or value that has been stored in it. A vector of datatype ‘int’ with the given size of 3 storing the value 15 is created which means the vector ‘v3’ is storing the following:

Vector<int> v3 = {15, 15, 15};

Major operations:

The major operations that we are going to implement on the vectors inside the vector class are:

  • Adding a value
  • Accessing a value
  • Altering a value
  • Deleting a value

Addition and deletion:

The addition and deletion of the elements inside the vector are done systematically. In most cases, elements are inserted at the finishing of the vector containers but you can also add values in the desired place which will eventually shift the other elements to their new locations. Whereas, in the deletion, when the values are deleted from the last position, it will automatically reduce the size of the container. But when the values inside the container are deleted randomly from a particular location, the new locations are assigned to the other values automatically.

Functions used:

To alter or change the values stored inside the vector, there are some pre-defined functions known as modifiers. They are as follows:

  • Insert(): It is used for the addition of a value inside a vector container at a particular location.
  • Erase(): It is used for the removal or deletion of a value inside a vector container at a particular location.
  • Swap(): It is used for the swap of the values inside a vector container that belongs to the same data type.
  • Assign(): It is used for the allocation of a new value to the previously stored value inside the vector container.
  • Begin(): It is used for returning an iterator inside a loop that addresses the first value of the vector inside the first element.
  • Clear(): It is used for the deletion of all of the values stored inside a vector container.
  • Push_back(): It is used for the addition of a value at the finishing of the vector container.
  • Pop_back(): It is used for the deletion of a value at the finishing of the vector container.

Example:

In this example, modifiers are used along the vectors.

First, we are including the <iostream> and <vector> header files. After this, the namespace std is integrated to add the classes all at once. For writing the entire program’s logic, we are calling the main() function where a vector named ‘digits’ is initialized. This vector’s assignment is done in the next step where ‘digits’ has given a value of 6 and 24, which means that 6 elements are stored inside the vector container, each with the value of 24. These values are then displayed using the ‘cout’ command. A ‘for’ loop is utilized for the modifier function push_back() for the addition of the elements inside the container. Now, 3 value is added to the digits at the end. The, we initialize a variable ‘x’ for keeping the record of the size of the vector container. Now, the last element’s value is displayed and the pop_back() function would delete the number ‘3’ stored inside the container. For the display of all the elements, we are using a ‘for’ loop again with the insert() modifier that will insert the values. Here, 4 will be inserted at the beginning of the vector container and displayed on the screen. The clear() modifier will then clear or delete all the values stored inside the container. The size of the vector is then shown after the clearing is done.

The output is shown below.

C++ Files Input Output:

A file is an assemblage of interrelated data. In C++, a file is a sequence of bytes that are collected together in chronological order. Most of the files exist inside the disk. But also hardware devices like magnetic tapes, printers, and communication lines are also included in the files.

The input and output in files are characterized by the three main classes:

  • The ‘istream’ class is utilized for taking input.
  • The ‘ostream’ class is employed for displaying output.
  • For input and output, use the ‘iostream’ class.

Files are handled as streams in C++. When we are taking input and output in a file or from a file, the following are the classes that are used:

  • Ofstream: It is a stream class that is used for writing onto a file.
  • Ifstream: It is a stream class that is utilized to read content from a file.
  • Fstream: It is a stream class that is used for both reading and writing in a file or from a file.

The ‘istream’ and ‘ostream’ classes are the ancestors of all the classes that are mentioned above. The file streams are as easy to use as the ‘cin’ and ‘cout’ commands, with just the difference of associating these file streams to other files. Let us see an example to study briefly about the ‘fstream’ class:

Example:

In this instance, we are writing data in a file.

We are integrating the input and output stream in the first step. The header file <fstream> is then added because we are going to write and read data from the file. After this, classes are called with the help of the namespace. The main() function is called for the program’s body where the ‘ofstream’ is used that writes the data into a file, the file is created as New_File. In the next step, we are opening up a text file named ‘example’ by utilizing the open() method. We are writing a text with the help of angular brackets into the file. Every file is destined to be closed once it has been tackled. This is why the file is closed with the help of the close() function.

File ‘example’ is opened from the personal computer and the text written on the file is imprinted onto this text file as shown above.

Opening a file:

When a file is opened, it is represented by a stream. An object is created for the file like New_File was created in the previous example. All of the input and output operations that have been done on the stream are automatically applied to the file itself. For the opening of a file, the open() function is used as:

Open(NameOfFile, mode);

Here, the mode is non-compulsory.

Closing a file:

Once all the input and output operations are finished, we need to close the file that was opened for editing. We are required to employ a close() function in this situation.

New_File.close();

When this is done, the file becomes unavailable. If under any circumstances the object is destroyed, even being linked to the file, the destructor will spontaneously call the close() function.

Text files:

Text files are used to store the text. Therefore, if the text is either entered or displayed it shall have some formatting alterations. The writing operation inside the text file is the same as we perform the ‘cout’ command.

Example:

In this scenario, we are writing data in the text file that was already made in the previous illustration.

Here, we are writing data in the file named ‘example’ by using the New_File() function. We open the file ‘example’ by using the open() method. The ‘ofstream’ is used to add the data to the file. After doing all the work inside the file, the required file is closed by the use of the close() function. If the file does not open the error message ‘File is not supported, error while loading file’ is shown.

The file opens and the text is displayed on the console.

Reading a text file:

The reading of a file is shown with the help of the succeeding example.

Example:

The ‘ifstream’ is utilized for reading the data stored inside the file.

The example includes the major header files <iostream> <fstream> <string> in the beginning. Then, use ‘ifstream’ inside the main() function. With the help of ‘ifstream’, we will read the data with the file ‘New_File’ showing the text stored inside the ‘example’ text file. We employ the open() method to open the file. Next, we will utilize the ‘while’ loop. After reading the data from the ‘example’ text file, the close() function is utilized to close the required file. If the system does not have the particular file, then we get the message ‘Unable to open file’.

All of the information stored inside the text file is displayed on the screen as shown.

Conclusion

In the above guide, we have learned about the C++ language in detail. Along with the examples, every topic is demonstrated and explained, and each action is elaborated.

About the author

Ann-ul Hayyat

I'm a professional SEO and technical content writer with extensive experience in these fields as well as writing content for blogs, websites, reports, and other topics related to education, science, sports, and many other areas. I am skilled and experienced in creating SEO-friendly blog posts, technical articles, and other content on themes that you may find interesting.