C++ Tutorial For Beginners

Table of Contents

What is C++?

C++ is a cross-platform language that is used to create high-performance applications. Bjarne Stroustrup developed it as an extension to the C language. C++ gives programmers control over the system resources and memory. The language was updated three significant times in 2011, 2014, and 2017 to C++11, C++14, and C++17. 

Why Use C++

  • C++ is one of the most popular languages for programming.
  • C++ can be found in operating systems, GUIs, and embedded systems.
  • It is an object-oriented programming language that gives a clear structure to programs and allows code to be reused, lowering development costs.
  • It is portable and can be used to develop applications that can be adapted to multiple platforms.
  • As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa.

Features

  • Simple: C++ is a simple language because it provides a structured approach to a rich set of functions, data types, etc.
  • Portable: Unlike the assembly language, c programs are being executed in many machines with little or no change. But it is not platform-independent.
  • Mid-level programming language: C++ is used to do low-level programming. It is used to develop applications such as the kernel, driver, etc. It also supports the feature of the high-level language. 
  • Structured programming language: C++ is a structured programming language because you can break the program into parts using functions.
  • Rich Library: C++ provides inbuilt functions that make the development fast.
  • Memory Management: It offers you the feature of dynamic memory allocation. You can free the allocated memory by calling the free() function.
  • Speed: The compilation and execution time of the C++ language is fast.
  • Pointer: C++ offers the feature of pointers. You can directly interact with the memory by using pointers.
  • Recursion: In C++, you can call the function within the function. It provides code reusability for every function.
  • Extensible: C++ language is extensible because it can quickly adopt new features.
  • Object-Oriented: C++ is an object-oriented programming language. OOPs makes maintenance and development easier, whereas, in Procedure-oriented programming language, it is not easy to manage if code grows as the project size increases.
  • Compiler based: It is a compiler-based programming language. First, you need to compile the program using a compiler, and then you can run the program.

Local Environment Setup

It would be good if you had the following software on your computer.

  • C++ Compiler

It is an actual C++ compiler, which will be used to compile your source code into the final executable program. Most C++ compilers do not care what extension you give to your source code. The most frequently used compiler is the GNU C/C++ compiler. 

  • Text Editor

It is used by the software to type. Examples include Windows Notepad, OS Edit, Short, Epsilon, EMACS, and Vim or VI commands. The files you generate with the editor are referred to as source files, and the C++ files are referred to as .cpp, .cp, or .c. To begin your C++ programming, a text editor must be in place.

  • Basic Syntax

Let us now look into what a class, object, methods, and instance variables mean.

  • Object − Objects have states and behaviors. Example: A cat has conditions – color, name, breed, and actions – wagging, meowing, eating. An object is an instance of the class.
  • Class − A class is defined as a blueprint that describes the behaviors/states that an object of its type support.
  • Methods − A method is behavior. A class can contain many methods. In methods where the logic is written, data is manipulated, and the actions are executed.
  • Instance Variables − There is a unique collection of instance variables in each object. The condition of an entity is generated by the values assigned to these example variables.

EXAMPLE

#include <iostream>
using namespace std;
int main() {
   cout << "Hello World"; 
   return 0;
}

OUTPUT

Hello World

Let’s look at the various parts of the program mentioned above −

  • It requires a header <iostream>. 
  • Use the namespace std; to warn the compiler to use the namespace std. 
  • The line int main() is the main feature where execution of the programme starts. 
  • The next line cuts to << “Hello World”; the word “Hello World” is reflected on the keyboard. 
  • The next line returns 0; the main()function terminates.

C++ Basic Input/Output

C++ I/O operation is using the stream concept. The stream is the sequence of bytes or flow of data. It makes the performance fast.

If bytes flow from the main memory to a device like a printer, display screen, or a network connection, etc., this is known as output operation.

If bytes flow from a device such as a printer, display screen, a network connection, etc., to main memory, this is called an input operation.

Standard Output Stream (cout)

The cout is a predefined object of the ostream class. It is connected with the output device, which is usually a display screen. The cout is used to join with the stream insertion operator to display the output on a console

EXAMPLE

#include <iostream>  
using namespace std;  
int main( ) 
{  
char ary[] = "Welcome to the end game";  
 cout << "Value of ary is: " << ary << endl;  
}  

OUTPUT

Value of ary is: Welcome to the end game

Standard Input Stream (cin)

The cin is a predefined object. It is connected with the input device, which is usually a keyboard. The cin is used to join the stream extraction operator (>>) to read the console input.

EXAMPLE

#include <iostream>  
using namespace std;  
int main( ) {  
int age;  
cout << "Enter age: ";  
cin >> age;  
cout << "Your age is: " << age << endl;  
}  

OUTPUT

Enter age: 21
Your age is: 21

Standard end line (endl)

The endl is a predefined object of the class. It is used to insert new line characters and flushes the stream.

EXAMPLE

#include <iostream>  
using namespace std;  
int main( ) 
{  
cout << "C++";     
cout << " Is Fun"<<endl;   
cout << "End of line"<<endl;   
}   

OUTPUT

C++ Is Fun
End of line

C++ Variables

A variable is the name of a memory location. It is used to store data. The value can be changed, and it is reused many times. It is a way to represent the memory location through a symbol to be easily identified. A variable can have alphabets, underscore, and digits. A variable name can start with an alphabet and underscore only. It can’t start with a digit.

No white spaces are allowed within the variable name.

A variable name must not be any reserved word or keyword, e.g., char, float, etc.

Valid variable names:

  • int a;    
  • int _ab;    
  • int a30;    

Invalid variable names:

  • int 4;    
  • int x y;    
  • int double;

C++ Identifiers

A C++ identifier is used to identify a variable, function, class, module, or any other user-defined item. It starts with A to Z or a to z or an underscore (_), which is followed by zero or more letters and 0 to 9. C++ does not allow punctuations such as @, $, and % within identifiers. It is a case-sensitive programming language. Thus, Workforce and workforce are two different identifiers in C++. 

C++ Data Types

TypeKeywords
Characterchar
Booleanbool
Floating pointfloat
Double floating pointdouble
Integerint
Valuelessvoid
Wide characterwchar_t
TypeTypical Bit WidthTypical Range
char1byte-127 to 127 or 0 to 255
unsigned char1byte0 to 255
signed char1byte-127 to 127
wchar_t2 or 4 bytes1 wide character
int4bytes-2147483648 to 2147483647
unsigned int4bytes0 to 4294967295
signed int4bytes-2147483648 to 2147483647
short int2bytes-32768 to 32767
float4bytes
unsigned short int2bytes0 to 65,535
signed short int2bytes-32768 to 32767
long int8bytes-2,147,483,648 to 2,147,483,647
signed long int8bytessame as long int
unsigned long int8bytes0 to 4,294,967,295
long long int8bytes-(2^63) to (2^63)-1
unsigned long long int8bytes0 to 18,446,744,073,709,551,615
double8bytes
long double12bytes

C++ Constants/Literals 

Constants refers to the fixed values that the program may alter and they are called literals.

Constants can be of any of the raw data types and are divided into Integer Numerals, Characters, Floating-Point Numerals, Strings, and Boolean Values.

Integer Literals

An integer literal is a decimal, octal, or hexadecimal constant. 

An integer literal has a suffix that is a combination of L and U, for long and unsigned, respectively. The suffix can be lowercase or uppercase and can be in any order.

 For e.g: 212, 215u, 0xFeeL, 078, 032UU       

Floating-point Literals

A floating-point literal has an integer part, a fractional part, a decimal point, and an exponent part. You can represent the floating-point literals either in decimal form or exponential form.

While representing using the decimal form, you must include the decimal point, the exponent, or both. While meaning using the exponential form, you must have the fractional part, the integer part, or both. The signed exponent is introduced by E or e.

Boolean Literals

There are two Boolean literals

  • A value of true representing true.
  • A value of false representing false.

Character Literals

Character literals are enclosed in single quotes. If the literal begins with L, it is a wide-character literal and should be stored in a wchar_t type of variable. Otherwise, it is a narrow character literal and is stored in a simple variable of char type.

Escape sequenceMeaning
\\\ character
\’‘ character
\”” character
\?? character
\aAlert or bell
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\oooOctal number of one to three digits
\xhh . . .Hexadecimal number of one or more digits

C++ Storage classes

The auto Storage Class

It is a default storage class for all local variables.

SYNTAX

{
   int mount;
   auto int month;
}

The register Storage Class

They are used to define local variables that are stored in a register instead of RAM. It means that the variable has a maximum size equal to the register size and cannot have the ‘&’ operator applied to it.

SYNTAX

{
   register int miles;
}

The static Storage Class

It tells the compiler to keep the local variable in existence during the program instead of creating and destroying it. So making local variables static offers them to maintain their values between function calls.

The extern Storage Class

It is used to give the reference of a global variable that is visible to every program file. When you use ‘extern’ the variable can’t be initialized.

The mutable Storage Class

The mutable specifier applies to the class objects. It offers a member of an object to override the const member function. That is, a mutable member can be modified by a const member function.

C++ Modifiers Types

C++ offers the char, int, and double data types to have modifiers preceding them. A modifier is used to change the meaning of the base type so that it more precisely fits the needs of various situations.

The data type modifiers are mentioned below−

  • signed
  • unsigned
  • long
  • short

The modifiers signed, unsigned, long, and short are applied to integer base types. In addition, signed and unsigned are applied to char, and long is applied to double.

The modifiers signed and unsigned are used as prefixes to long or short modifiers. 

Types of qualifiers

  • const: Objects of type const can’t be changed by the program during execution.
  • volatile: The modifier volatile tells the compiler that the value of the variable may be changed in ways not explicitly specified by the program.
  • restrict: A pointer qualified by restrict is the only means by which the object it points to can be accessed. The C99 adds a new type of qualifier called restrict.

EXAMPLE

#include <iostream>
using namespace std;
int main() 
{
   short int i;   
   short unsigned int j; 
   j = 50000;
   i = j;
   cout << i << " " << j;
   return 0;
}

OUTPUT

-15536 50000

Operators in C++

An operator is a symbol that helps the compiler to perform specific mathematical or logical manipulations. C++ has various built-in operators and offers the following types of operators −

  • Arithmetic Operator
  • Logical Operator
  • Bitwise Operator
  • Assignment Operator
  • Relational Operator
  • Misc Operator

Arithmetic Operator

Arithmetic operators are nothing but the operators that are used to perform arithmetic operations between variables or two values.

OperatorsDescriptionSyntax
+Adds two operandsa+b
*Multiplies two operandsa*b
Subtracts two operandsa-b
/Divides the first operand by the seconda/b
%Returns the remainder when the first operand is divided by the seconda%b
++It increases integer value by onea++
It decreases integer value by onea–

Logical operator

The logical operators in C++ combine the true or false values of variables so you can figure out their resultant truth value.

OperatorsDescriptionSyntax
Or (||)True if either of the operands is true(A || B) is true.
And (&&)True if both the operands are true(A && B) is false.
Not (!)If a condition is true, then the Logical NOT operator will make false.!(A && B) is true.

Bitwise operator

In C++ bitwise operators perform bitwise calculations on integers. Bitwise operator: Returns 1 if both the bits are 1 else 0. Example: a = 10 = 1010 (Binary) b = 4 = 0100 (Binary a & b = 1010 & 0100 = 0000 = 0 (Decimal) Bitwise or operator: Returns 1 if either of the bit is 1 else 0.

OperatorsDescriptionSyntax
>>Binary right shift x>>x>>
<< Binary left shift x<<
Binary XORx ^ y
&Binary ANDx & y
|Binary ORx | y
~Binary NOT~x

Assignment Operator

Assignment operators assign values to the variables. a = 5 is an assignment operator that sets the value 5 on the right to the variable an on the left. 

OperatorsDescriptionSyntax
=Assigning values of the right side’s expression to the left side’s operand.a=b+c
+=Add right’s side operand with left side’s operand and then assign to the left operand.a+=b a=a+b
-=Subtract the right’s operand from the left’s operand and then assign it to the left operand.a-=b  a=a-b
/=Divide left’s operand with right’s operand and then assign to the left operand.a/=b  a=a/b
%=Take modulus using the left and right operand and assign the result to the left operand.a%=b a=a%b    
*=Calculate exponent value using operands and assign value to the left operand.a*=b  a=a*b
&=Performs Bitwise AND on operand and assigns value to the left operand.a&=b  a=a&b
|=    Performs Bitwise OR on operand and assigns value to the left operand.a|=b  a=a|b
^=Performs Bitwise OR on operand and assigns value to the left operand.a^=b   a=a^b
>>=Perform Bitwise right shift on operand and assign value to the left operand.a>>=b  a=a>>b
<<=Performs Bitwise left shift on operand and assign value to left operand.a <<= b   a= a << b

Relational operator

Relational operators are the operators that are used to compare two values or objects.

OperatorsDescriptionSyntax
Greater than x > y
<Less thanx < y
== Equalx == y
!= Not equalx != y
>= Greater than or equal to x >= y
<= Less than or equal tox <= y

Misc Operators

OperatorDescription
Condition ? X : YIf the condition is true, then it returns the value of X otherwise returns the value of Y.
,It causes a sequence of operations to be performed. The value of the comma is the value of the last expression of the list separated by a comma.
sizeofIt returns the size of a variable. For example, sizeof(a), where ‘a’ is an integer and will return 4.
*It is a pointer to a variable. For example *var; will pointer to a variable var.
CastIt converts one data type to another. 
. (dot) and -> (arrow)They are used to reference individual members of classes, structures, and unions.
&It returns the address of the variable.

C++ Loops

for loop 

The C++ for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop than while or do-while loops.

The C++ for loop is the same as C/C#. We can initialize variables, check the condition, and increment/decrement value.

SYNTAX

for(initialization; condition; incr/decr)
{       
}    

EXAMPLE

#include <iostream>  
using namespace std;  
int main() {  
         for(int i=1;i<=10;i++){      
            cout<<i <<"\n";      
          }       
  }  

OUTPUT

1
2
3
4
5
6
7
8
9
10

Nested For Loop

In C++, you can use for loop inside another for loop. It is known as nested for loop. The inner loop is executed fully when the outer loop is executed one time. So if the outer loop and inner loop are executed four times, the inner loop will be executed four times for each outer loop, i.e., a total of 16 times.

EXAMPLE

#include <iostream>  
using namespace std;  
int main () {  
        for(int i=1;i<=3;i++){      
             for(int j=1;j<=3;j++){      
            cout<<i<<" "<<j<<"\n";      
          }     
        }  
    }    

OUTPUT

1 1
1 2
1 3
2 1
2 2 
2 3
3 1
3 2
3 3

While loop 

In C++, while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use a while loop rather than for loop.

SYNTAX

while(condition)
{      
}   

EXAMPLE

#include <iostream>  
using namespace std;  
int main() 
{         
 int i=1;      
         while(i<=10)   
       {      
            cout<<i <<"\n";    
            i++;  
        }       
    }  

OUTPUT

1
2
3
4
5
6
7
8
9
10

Nested While Loop

In C++, you can use a while loop inside another while loop; it is known as a nested while loop. The nested while loop is executed when the outer loop is executed once.

EXAMPLE

#include <iostream>  
using namespace std;  
int main () 
{  
        int i=1;      
          while(i<=3)     
          {    
             int j = 1;    
              while (j <= 3)    
{      
            cout<<i<<" "<<j<<"\n";      
            j++;  
          }     
           i++;  
        }  
 }    

OUTPUT

1 1
1 2
1 3
2 1
2 2 
2 3
3 1
3 2
3 3

Do-while loop 

The C++ do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must execute the loop at least once, it is recommended to use a do-while loop.

The C++ do-while loop is executed at least once because the condition is checked after the loop body.

SYNTAX

do
{    
}while(condition);  

EXAMPLE

#include <iostream>  
using namespace std;  
int main() 
{  
     int i = 1;    
          do
  {    
              cout<<i<<"\n";    
              i++;    
          } while (i <= 10) ;    
}  

OUTPUT

1
2
3
4
5
6
7
8
9
10

Nested Do-While Loop

In C++, if you use a do-while loop inside another do-while loop, it is known as a nested do-while loop. The nested do-while loop is executed fully for each outer do-while loop.

EXAMPLE

#include <iostream>  
using namespace std;  
int main() 
{  
     int i = 1;    
         do
{    
              int j = 1;          
              do
    {    
                cout<<i<<"\n";        
                  j++;    
              } while (j <= 3) ;    
              i++;    
          } while (i <= 3) ;     
}  

OUTPUT

1 1
1 2
1 3
2 1
2 2 
2 3
3 1
3 2
3 3

Decision making Statements

There are situations in real life when you need to make some decisions, and based on these decisions, you decide what you should do next. Similar problems arise in programming also where you need to make some decisions, and based on these decisions, you will execute the next block of code.

Decision-making statements in programming languages decide the direction of the flow of program execution. Decision-making statements available in C++ are:

  • if statement
  • if..else statements
  • nested if statements
  • if-else-if ladder
  • Jump Statements:
    • break
    • continue
    • goto
    • return

if statement

if statement is a simple decision-making statement. It is used to decide whether the block of statements will be executed or not. If the condition is true then a block of statement is executed otherwise not.

SYNTAX

if(condition) 
{
}

Here, conditions after evaluation will be either true or false. if statement accepts boolean values.

EXAMPLE

#include<iostream> 
using namespace std; 
int main() 
    { 
        int i = 10; 
   if (i > 15) 
        { 
           cout<<"10 is less than 15"; 
        }    
         cout<<"I am if"; 
    } 

OUTPUT

I am if

if else statement

The if statement tells that if a condition is true it will execute the block of statements and if the condition is false it will not execute. You can use the else statement with if statement to execute a block of code when the condition is false.

SYNTAX

if (condition)
{
    // Execute this block if
    // condition is true
}
else
{
    // Execute this block if
    // condition is false
}

EXAMPLE

#include<iostream> 
using namespace std; 
int main() 
 { 
        int i = 25; 
       if (i < 20) 
            cout<<"i is smaller than 20"; 
        else
            cout<<"i is greater than 20";    
    return 0;    
 } 

OUTPUT

i is greater than 20

Nested if statements

A nested if in C++ is an if statement that targets another if statement. Nested if statements mean that an if statement inside another if statement. Yes, both C and C++ offer us nested if statements within if statements, i.e., you can place an if statement inside another if statement.

SYNTAX

if (condition1) 
{
   // Execute when condition1 is true
   if (condition2) 
   {
      // Execute when condition2 is true
   }
}

EXAMPLE

#include <iostream> 
using namespace std; 
int main() 
{ 
    int i = 10; 
    if (i == 10) 
    { 
        if (i < 15) 
           cout<<"i is smaller than 15\n"; 
        if (i < 12) 
            cout<<"i is smaller than 12 \n"; 
        else
            cout<<"i is greater than 15"; 
    } 
    return 0; 
} 

OUTPUT

i is smaller than 15
i is smaller than 12 

if-else-if ladder

A user can decide among various options. The if statements are executed from top-down. As soon the conditions control the if is true, then the statement associated with that is executed, and the rest else-if ladder is terminated. If the conditions are not true, then the last and final statement will be performed.

SYNTAX

if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;

EXAMPLE

#include<iostream> 
using namespace std; 
int main() 
{ 
    int i = 20; 
    if (i == 10) 
        cout<<"i is 10"; 
    else if (i == 15) 
        cout<<"i is 15"; 
    else if (i == 20) 
        cout<<"i is 20"; 
    else
        cout<<"i is not present"; 
} 

OUTPUT

i is 20

Jump Statements

Break

This statement is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there and control returns immediately to the first statement after the loop.

SYNTAX
Break;

Break statements are used in situations when we are not sure about the actual number of iterations for the loop or terminate the loop based on some condition.

EXAMPLE

#include <iostream> 
using namespace std; 
void findElement(int arr[], int size, int key) 
{ 
    for (int i = 0; i < size; i++) 
{ 
        if (arr[i] == key) 
{ 
            cout << "An element found at position: " << (i + 1); 
            break; 
        } 
} 
}  
int main() 
{ 
    int arr[] = { 1, 2, 3, 4, 5, 6 }; 
    int n = 6;  
    int key = 3;  
    findElement(arr, n, key); 
    return 0; 
} 

OUTPUT

An element found at position: 3

Continue

The continue statement is the opposite of the break statement; instead of terminating the loop, it forces the next iteration of the loop.

The continue statement forces the loop to execute the next iteration. When the continue statement is executed, the code inside the loop following the continue statement is skipped, and the next iteration will begin.

SYNTAX

An element found at position: 3

EXAMPLE

#include <iostream> 
using namespace std; 
int main() 
{ 
    for (int i = 1; i <= 9; i++)
{ 
        if (i == 6) 
            continue; 
        else
            cout << i << " "; 
   } 
      return 0; 
} 

OUTPUT

1 2 3 4 5 7 8 9 

Go to

The goto statement in C++ refers to an unconditional jump statement that is used to jump from one point to another within a function.

SYNTAX

Syntax1     | Syntax2
----------------------------
goto label; | label:  
.       | .
.       | .
.       | .
label:          | goto label;

EXAMPLE

#include <iostream> 
using namespace std;  
void printNumbers() 
{ 
    int n = 1; 
label: 
    cout << n << " "; 
    n++; 
    if (n <= 10) 
        goto label; 
} 
int main() 
{ 
    printNumbers(); 
    return 0; 
} 

OUTPUT

1 2 3 4 5 6 7 8 9 10

Return

The return in C++ returns the flow of the execution to the function. This statement does not need any conditional statements. Once the statement is executed, the program’s flow stops immediately and returns the control from where it was called. The return statement might or might not return anything for a void function, but a return value must be returned for a non-void function.

SYNTAX

1 2 3 4 5 6 7 8 9 10

EXAMPLE

#include <iostream> 
using namespace std; 
int SUM(int a, int b) 
{ 
    int s1 = a + b; 
    return s1; 
}
void Print(int s2) 
{ 
    cout << "The sum is "<< s2; 
    return; 
} 
int main() 
{ 
    int num1 = 10; 
    int num2 = 10; 
    int sum_of = SUM(num1, num2); 
    Print(sum_of); 
    return 0; 
} 

OUTPUT

The sum is 20

C++ Functions

A function refers to a group of statements that takes the input, processes it, and returns the output. The objective of the function is to combine tasks that are done again and again. If you are having various inputs, you need not write the same code again. You can call the function with a different set of data known as parameters.

C++ program has at least one function, the main() function.

Defining a Function

A function definition in C++ consists of a function header and a body.

  • Return Type − It may return a value. Some functions perform the operations without returning a value. In this, the return_type is the keyword void.
  • Function Name − It is the actual name of the function. The function name and the list together constitute the function signature.
  • Parameters − A parameter is just like a placeholder. When a function is invoked, you pass the value to the parameter. This value is known as an actual parameter or argument. The parameter list refers to the order, type, and a number of a function’s parameters. 
  • Function Body − The body contains a collection of statements that define what the function does.

EXAMPLE

int max(int num1, int num2)
 {
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result; 
}

Declaring a Function

In C++, the functions must be declared before they are used. You can declare a function by providing its return value, name, and the types for its arguments. The terms of the arguments are optional. A function definition counts as a function declaration.

EXAMPLE

#include < iostream>
using namespace std;
int sum (int x, int y);
int main()
{
    int a = 20;
    int b = 30;
    int c = sum (a, b);  
    cout << c;
}
int sum (int x, int y)
{
    return (x + y);
}

Calling a function

While you create a C++ function, you define what the function has to do. To use a function, you need to call or invoke that function.

When the program calls a function, program control is transferred to the called function. A called function performs a defined task, and when it’s return statement is executed or when its function-ending closing brace is reached, it returns program control to the main program.

EXAMPLE

#include <iostream>
using namespace std;
int max(int num1, int num2);
int main () 
{
   int a = 100;
   int b = 200;
   int ret;
   ret = max(a, b);
   cout << "Max value is : " << ret << endl;
   return 0;
}
int max(int num1, int num2) {
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result; 
}

Function Arguments

If a function uses arguments, it should declare variables that accept the arguments’ values. These variables are known as the formal parameters of the function.

  • Call by Value: It copies the actual value of the argument into the formal parameter of the function. The changes made to the parameter inside the function do not affect the argument.
  • Call by Pointer: It copies the address of the argument into the formal parameter. Inside this function, the address is used to access the argument used in the call. It means that the changes made to the parameter affect the argument.
  • Call by Reference: It copies the reference of an argument into the formal parameter. Inside this function, the reference is used to access the argument used in the call. This means that the changes made to the parameter affect the argument.

C++ Numbers

Usually, when we work with Numbers, we use primitive data types such as int, short, long, float, double, etc. The number of data types, their possible values, and number ranges have been explained while discussing C++ Data Types.

EXAMPLE

#include <iostream>
using namespace std;
int main ()
 {
   short  s;
   int    i;
   long   l;
   float  f;
   double d;
   s = 10;      
   i = 1000;    
   l = 1000000; 
   f = 230.47;  
   d = 30949.374;
   cout << "short  s :" << s << endl;
   cout << "int    i :" << i << endl;
   cout << "long   l :" << l << endl;
   cout << "float  f :" << f << endl;
   cout << "double d :" << d << endl;
   return 0;
}

OUTPUT

short  s :10
int    i :1000
long   l :1000000
float  f :230.47
double d :30949.4

Math operators in C++

S.NOFunctions Purpose
1double sin(double);It takes an angle (as a double) and returns the sine.
2double cos(double);It takes an angle (as a double) and returns the cosine.
3double tan(double);It takes an angle (as a double) and returns the tangent.
4double pow(double, double);The first is a number you wish to raise and the second is the power you wish to raise it t
5double log(double);It takes a number and returns the natural log of that number.
6double hypot(double, double);If you pass this the length of two sides of a right triangle, it will return you the length of the hypotenuse.
7double sqrt(double);You pass the function a number and it gives you the square root.
8int abs(int);It returns the absolute value of an integer that is passed to it.
9double floor(double);Finds the integer which is less than or equal to the argument passed to it.
10double fabs(double);It returns the absolute value of any decimal number passed to it.

EXAMPLE

#include <iostream>
#include <cmath>
using namespace std;
int main () 
{ 
   short  s = 10;
   int    i = -1000;
   long   l = 100000;
   float  f = 230.47;
   double d = 200.374;
   cout << "sin(d) :" << sin(d) << endl;
   cout << "abs(i)  :" << abs(i) << endl;
   cout << "floor(d) :" << floor(d) << endl;
   cout << "sqrt(f) :" << sqrt(f) << endl;
   cout << "pow( d, 2) :" << pow(d, 2) << endl;
   return 0;
}

OUTPUT

sign(d)     :-0.634939
abs(i)      :1000
floor(d)    :200
sqrt(f)     :15.1812
pow( d, 2 ) :40149.7

C++ Arrays

An array in C++ is a collection of items stored at contiguous memory locations, and elements can be accessed randomly using an array’s indices. They are used to store similar elements as the data type must be the same for all elements. They can store primitive data types such as char, int, float, double, etc. To add to it, an array in C++ can store derived data types such as the structures, pointers, etc. Given below is the picturesque representation of an array.

Array Declaration

SYNTAX

dataType arrayName[arraySize];

EXAMPLE

int y[4];

Here,

  • int – a type of element to be stored
  • y – the name of the array
  • 4 – the size of the array

Access Elements in Array

Each element in an array is connected with a number. The number is called an array index. You can access the elements of an array by using the indices.

SYNTAX

Array[index];

EXAMPLE

#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () 
{
   int n[ 10 ]; 
   for ( int i = 0; i < 10; i++ ) 
{
   n[ i ] = i + 100; 
  }
    cout << "Element" << setw( 13 ) << "Value" << endl;                     
    for ( int j = 0; j < 10; j++ ) 
{
    cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
  }
   return 0;
}

Here are a few important concepts of C++ arrays

  • Multi-dimensional arrays: A two-dimensional array is the simplest form of the multidimensional array.
  • Pointer to an array: You will generate a pointer to the first element of an array by mentioning the array name without the index.
  • Passing arrays to functions: You will pass to the function a pointer to an array by specifying the array’s name without an index.
  • Return array from functions: C++ allows the function to return an array.

C++ Strings

It is a collection of characters. There are two types of strings used in the C++ programming language:

  • Strings that are objects of string class
  • C-strings

The string class

The C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality.

EXAMPLE

#include <iostream>
#include <string>
using namespace std;
int main () 
{
   string str1 = "Hello";
   string str2 = "World";
   string str3;
   int  len ;
   str3 = str1;
   cout << "str3 : " << str3 << endl;
   str3 = str1 + str2;
   cout << "str1 + str2 : " << str3 << endl;
   len = str3.size();
   cout << "str3.size() :  " << len << endl;
   return 0;
}

OUTPUT

str3 : Hello
str1 + str2 : HelloWorld
str3.size() :  10

C strings

This string originated within the C language and is supported within C++. This string is a one-dimensional array of characters that is terminated by a null character ‘\0’. Thus the null-terminated string contains the characters that comprise the string followed by a null.

EXAMPLE

#include <iostream>
using namespace std;
int main () 
{
   char greeting[6] = {'H', 'E', 'L', 'L', 'O', '\0'};
   cout << "Greeting message: ";
   cout << greeting << endl;
   return 0;
}

OUTPUT

Greeting message: HELLO

Few functions that manipulate null-terminated strings

  • strcpy(s1, s2);

It copies the string s2 into the string s1.

  • strcat(s1, s2);

It concatenates the string s2 onto the end of string s1.

  • strstr(s1, s2);

It returns a pointer to the occurrence of string s2 in string s1.

  • strlen(s1);

It returns the length of string s1.

  • strcmp(s1, s2);

It returns 0 if s1 and s2 are same; less than 0 if s1<s2; greater than 0 if s1>s2.

  • strchr(s1, ch);

It returns the pointer to the occurrence of the character ch in string s1.

C++ Pointers

Pointers are a representation of addresses. They enable programs to simulate call-by-reference and to create and manipulate dynamic data structures. 

SYNTAX

datatype *var_name; 
int *ptr;

How to use a pointer?

  • First, define a pointer variable
  • Now assign the address of the variable to a pointer using (&) which returns the address of that variable.
  • Accessing the values stored in the address using (*) which returns the value of the variable located at the address specified by its operand.

Few concepts of pointers

  • Null Pointers: It is a constant with a value of zero defined in various standard libraries.
  • Pointer Arithmetic: Four arithmetic operators can be used on pointers: ++, –, +, –
  • Pointers vs Arrays: There is a close connection between pointers and arrays.
  • Array of Pointers: You can define arrays to hold several pointers.
  • Pointer to Pointer: C++ offers you to have a pointer on a pointer and so on.
  • Passing Pointers to Functions: Passing by reference or by address both enable the given statement to be changed in the calling function by the called function.
  • Return Pointer from Functions: C++ offers a function to return a pointer to a local variable, static variable, and dynamically allocated memory as well.

EXAMPLE

#include <bits/stdc++.h> 
using namespace std; 
void geeks() 
{ 
    int var = 20; 
    int *ptr; 
    ptr = &var;    
    cout << "Value at ptr = " << ptr << "\n"; 
    cout << "Value at var = " << var << "\n"; 
    cout << "Value at *ptr = " << *ptr << "\n";     
} 
int main() 
{ 
    geeks(); 
} 

OUTPUT

Value at ptr = 0x7ffcb9e9ea4c
Value at var = 20
Value at *ptr = 20

C++ References

A reference variable is a name for an already existing variable. Once a reference is initialized either the variable name or the reference name may be used to refer to the variable.

EXAMPLE

#include<iostream>
using namespace std;
int main()
{
  int x = 10;
  int& ref = x;
  ref = 20;
  cout << "x = " << x << endl ;
  x = 30;
  cout << "ref = " << ref << endl ;
  return 0;
}

OUTPUT 

 x = 20
ref = 30

C++ Date and Time

The C++ library does not provide a proper date type. It inherits the structs and functions for date and time manipulation from C. To access date and time-related functions and structures, you would need to include <ctime> header file in your C++ program.

There are four time-related types: clock_t, time_t, size_t, and tm. The types – clock_t, size_t, and time_t are capable of representing the system time and date as some integer.

EXAMPLE

#include <iostream>
#include <ctime>
using namespace std;
int main( )
{
time_t ttime = time(0);
char* dt = ctime(&ttime);
cout << "The current local date and time is: " << dt << endl;
tm *gmt_time = gmtime(&ttime);
dt = asctime(gmt_time);
cout << "The current UTC date and time is:"<< dt << endl;
}

Some important functions

  • time_t time(time_t *time);

It returns the current calendar time in several seconds elapsed since January 1, 1970. If the system has no time, then .1 is returned.

  • char *ctime(const time_t *time);

It returns a pointer to a string of the form day month year hours:minutes: seconds.

  • struct tm *localtime(const time_t *time);

It returns a pointer to the tm structure representing the local time.

  • clock_t clock(void);

It returns a value that approximates the time the calling program has been running. A value of .1 is returned if time is not available.

  • char * asctime ( const struct tm * time );

It returns a pointer to the string that contains the information stored in a structure pointed by time converted into the form: day month date hours:minutes: seconds 

  • struct tm *gmtime(const time_t *time);

It returns a pointer to the time in the form of a tm structure.

  • time_t mktime(struct tm *time);

It returns the calendar-time found in the structure pointed to by time.

  • double difftime ( time_t time2, time_t time1 );

It calculates the difference in seconds between time1 and time2.

  • size_t strftime();

It can be used to format date and time in a specific format.

C++ Data Structures

C++ arrays offer you to define variables that combine several data items of the same kind. Still, the structure is another user-defined data type which will enable you to combine data items of different sorts. Structures are used to represent a record.

Defining a Structure

To define a structure, you should use the struct statement. The struct statement defines a data type, with more than one member, for the program.

struct [structure tag] 
{
   member definition;
   member definition;
   member definition;
} 

The structure tag is optional. At the end of the definition, before the final semicolon, you should specify one or more structure variables.

Accessing Structure Members

To access any member of the structure, you can use the member access operator (.). The member access operator is coded as a period between a structure variable name and a structure member that we wish to access. You would use a struct keyword to define variables of structure type.

Structures as Function Arguments

You can pass the structure as a function argument in the same way as you pass any other variable or pointer.

EXAMPLE

#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books *book );
struct Books 
{
   char  title[100];
   char  author[150];
   char  subject[200];
   int   book_id;
}
int main() 
{
   struct Books Book1; 
   struct Books Book2;
   strcpy( Book1.title, "Learn C Programming");
   strcpy( Book1.author, "Joseph Stallin"); 
   strcpy( Book1.subject, "C Programming");
   Book1.book_id = 6495408;
   strcpy( Book2.title, "Telecom for Begginners");
   strcpy( Book2.author, "Stuart Zing");
   strcpy( Book2.subject, "Telecom");
   Book2.book_id = 6495705;
   printBook( &Book1 );
   printBook( &Book2 );
   return 0;
}
void printBook( struct Books *book ) 
{
   cout << "Book title : " << book->title <<endl;
   cout << "Book author : " << book->author <<endl;
   cout << "Book subject : " << book->subject <<endl;
   cout << "Book id : " << book->book_id <<endl;
}

OUTPUT

Book title: Learn C Programming
Book author: Joseph Stallin
Book id: 6495408
Book title: Telecom for Beginners
Book author: Stuart Zing
Book subject: Telecom
Book id: 6495705

C++ Classes and Objects

Everything in C++ is related to classes and objects, along with their attributes and methods. For example: in real life, a bus is an object. The bus has attributes, such as weight and color, and methods, such as drive and brake.

Attributes and methods are variables and functions that belong to the class. They are known as “class members”.The class is a user-defined data type that you can use in a program, and it works as an object constructor or a “blueprint” for creating objects.

Create a Class

If you want to create a class, you have to use the class keyword:

EXAMPLE

Create a class called "MyClass":
class MyClass 
{    
  public:
  int myNum;
  string myString;
};

Create an Object

In C++, an object is created from a class. 

To create an object you need to specify the class name, followed by the object name. To access the class attributes, use the dot syntax (.) on the object:

EXAMPLE

class MyClass 
{
  public:
  int myNum;
  string myString;
};
int main() 
{
MyClass myObj; 
myObj.myNum = 22; 
myObj.myString = "Some text";
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

Few concepts in detail

  • Class Member Functions: A member function is a function that has its prototype within the class definition just like any other variable.
  • Class Access Modifiers: A class member can be defined as private, public, protected. By default it is private.
  • Constructor: A constructor is a function in a class which is called when a new object is created.
  • Destructor: A destructor is a function which is called when created object is deleted.
  • Copy Constructor: It is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
  • Friend Functions: It gives full access to private and protected members of a class.
  • Inline Functions: The compiler expands the code in the body of the function in place of a call to the function.
  • this Pointer: Every object has a special pointer this which points to the object itself.
  • Static Members of a Class: Both the data members and function members of a class may be declared as static.

C++ Inheritance

Inheritance is a process in which an object acquires all the properties and behaviors of its parent object automatically. You can modify the attributes and actions which are defined in other classes.

The class which inherits the members of another class is known as a derived class, and a class whose members are inherited is known as a base class. The derived class is the specialized class for the base class.

Types Of Inheritance

  • Single inheritance is the type of inheritance in which the derived class is inherited from only one base class.

‘A’ is the base class,

‘B’ is a derived class.

cplusplus
  • Multilevel inheritance is a process of deriving a class from another derived class. Class C inherits the properties of the class B and class B inherits the properties of the class B.  A is the parent class of B and class B is the parent class of C. 
  • Multiple inheritance A derived class is created from one base class or more. Class C inherits the properties and behavior of class B and class A. So, here class A and class B are the parent classes for class C.
3nSGDaKe6InZqdcGuSiRLchWQpkuungECCSgU TUhXmfLU5ZG l3Okdi0zOJylAEHXyOL8fwSsqc D9kTjVwxK8Hfo9CvhEYWG SwjMMRIgdgyYqnuoJNUgdC w7VjRVAIAqOFiI
  • In Multipath inheritance, a derived class is created from another derived class and the same base class of another derived class. This inheritance is not supported by .NET Languages like C#, F#, etc.

Class D inherits the properties and behavior of class C and class B as well as Class A. Class C, and class B inherits the Class A. Class A is the parent for Class B and Class C and Class D. 

aMXAYwNkCn5ZcDG4cZc5Kq7tS5i 41sMKX112sfSt3AA8lHrF4GvXC8Qptz
  • Hybrid inheritance is a combination of more than one inheritances. Hence, it may be a combination of Multilevel inheritance and Multiple inheritance and Multilevel inheritance and Multipath inheritance Multilevel and Multiple inheritance.
Mfi2tAzYZ VCJUEb6l8X

C++ Access Modifiers

Access modifiers are used to implement an essential aspect of Object-Oriented Programming known as Data Hiding. Access Modifiers in a class are used to assign access to the class members. It sets some restrictions on the class members not to get directly accessed by the outside functions.

There are three types of access modifiers that are available in C++: 

  • Public
  • Private
  • Protected

Let us discuss them in detail:

Public

All the class members that are declared under the public specifier is available to everyone. The member functions declared as public can be accessed by other classes and functions too. The public members of a class can be accessed from anywhere in the program using the access operator (.) with that class’s object.

EXAMPLE

#include<iostream>
using namespace std;
class Circle
{
    public: 
        double radius;
        double compute_area()
        {
            return 3.14*radius*radius;
        }
};
int main()
{
    Circle obj;
    obj.radius = 5.5;
    cout << "Radius is: " << obj.radius << "\n";
    cout << "Area is: " << obj.compute_area();
    return 0;
}

OUTPUT

Radius is: 5.5
Area is: 94.985

Private 

The member functions inside the class can only access the class members that are declared private. They cannot be accessed directly by any object or function outside the class. Only the friend functions are allowed to access the private data of members of a class.

EXAMPLE

#include<iostream>
using namespace std;
class Circle
{  
    private: 
        double radius;
    public:   
        void compute_area(double r)
        { 
            radius = r;
            double area = 3.14*radius*radius;
            cout << "Radius is: " << radius << endl;
            cout << "Area is: " << area;
        }
};
int main()
{  
    Circle obj;
    obj.compute_area(1.5);
    return 0;
}

OUTPUT 

Radius is: 1.5
Area is: 7.065

Protected

A protected access modifier is the same as a private access modifier as it cannot be accessed outside of its class unless, with the help of a friend class, the difference is that the class members that are declared as Protected can be accessed by any derived class of that class as well.

EXAMPLE

OUTPUT

id_protected is: 81

C++ Overloading

C++ programming language allows you to specify more than one definition for a function name or an operator in the same scope, called function overloading and operator overloading, respectively.

An overloaded declaration is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and different definitions.

Function Overloading

Function overloading is a feature that offers you to have more than one function having the same name but a different parameter list.

EXAMPLE

#include <iostream>
using namespace std;
class Addition {
public:
    int sum(int num1,int num2) {
        return num1+num2;
    }
    int sum(int num1,int num2, int num3) {
       return num1+num2+num3;
    }
};
int main(void) {
    Addition obj;
    cout<<obj.sum(20, 15)<<endl;
    cout<<obj.sum(81, 100, 10);
    return 0;
}

OUTPUT

35
191

C++ Polymorphism

Operator overloading

You can make operators work for user-defined classes. This means C++ can provide the operators with a special meaning for a data type. This is known as operator overloading.

EXAMPLE

#include<iostream> 
using namespace std; 
class Complex 
{ 
private: 
    int real, image; 
public: 
    Complex(int r = 0, int i =0) {real = r;  image = i;} 
    Complex operator + (Complex const &obj) 
{ 
         Complex res; 
         res.real = real + obj.real; 
         res.image = image + obj.image; 
         return res; 
    } 
    void print() { cout << real << " + i" << image << endl; } 
}; 
int main() 
{ 
    Complex c1(10, 5), c2(2, 4); 
    Complex c3 = c1 + c2;
    c3.print(); 
} 

OUTPUT

12 + i9

It is an important concept of object-oriented programming. It means more than one form. That is, the same entity behaves differently in different scenarios.

Function Overriding

You can have the same function in the base class as well as the derived classes. When you call the function using an object of the derived class, the derived class’s function is executed rather than the base class.

Therefore, different functions are executed depending on the object calling the function. This is called function overriding

EXAMPLE

#include <iostream>
using namespace std;
class Base 
{
   public:
    virtual void print()
{
        cout << "Base Functions" << endl;
    }
};
class Derived: public Base 
{
   public:
    void print() {
        cout << "Derived Functions" << endl;
    }
};
int main() 
{
    Derived derived1;
    derived1.print();
    return 0;
}

OUTPUT

Derived Functions

C++ Virtual Functions

In C++, you may not be able to override functions if we use a base class pointer to point to an object of the derived class.

Using virtual functions in the base class ensures that the function can be overridden in these cases. Thus, virtual functions fall under function overriding.

Pure Virtual Functions

It is possible that you want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class.

EXAMPLE

class test
{
   protected:
      int width, height;
   public:
      test(int a = 0, int b = 0) 
     {
         width = a;
         height = b;
      }
      virtual int area() = 0;
};

C++ Data Abstraction

Data abstraction is one of the essential features of object-oriented programming in C++. Abstraction means displaying only relevant information and hiding the details. Data abstraction refers to providing only essential information about the outside world’s data, hiding the background details or implementation.

Abstraction using Classes

You can implement Abstraction in C++ with the help of classes. The class helps you to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to the outside world and which is not.

Abstraction using access specifiers

Access specifiers play a vital role in implementing abstraction in C++. You can use access specifiers to enforce restrictions on class members. For example:

  • Members declared as public in a class might be accessed from anywhere in the program.
  • Members declared as private in a class can be accessed only from within the class. They are not allowed to be accessed from any part of the code outside the class.

EXAMPLE

#include <iostream> 
using namespace std; 
class implementAbstraction 
{ 
    private: 
        int a, b; 
    public: 
        void set(int x, int y) 
        { 
            a = x; 
            b = y; 
        } 
        void display() 
        { 
            cout<<"a = " <<a << endl; 
            cout<<"b = " << b << endl; 
        } 
}; 
int main() 
{ 
    implementAbstraction obj; 
    obj.set(10, 20); 
    obj.display(); 
    return 0; 
} 

OUTPUT

a = 10
b = 20

C++ Data Encapsulation

It is the process of combining functions and data members in a single unit called class. This is to prevent access to the data directly. Access to them is provided through the functions of the class. It is one of the popular features of Object-Oriented Programming that helps in data hiding.

To implement this

  • Make all data members private.
  • Create a public setter and getter functions for each data member in such a way that the set function set the value of the data member, and the get function get the value of the data member

EXAMPLE

#include<iostream>
using namespace std;
class ExampleEncap
{
private:
   int num;
   char ch;
public:
   int getNum() const 
 {
      return num;
  }
   char getCh() const 
  {
      return ch;
   }
   void setNum(int num) 
  {
      this->num = num;
   }
   void setCh(char ch) 
  {
      this->ch = ch;
   }
};
int main()
{
   ExampleEncap obj;
   obj.setNum(100);
   obj.setCh('A');
   cout<<obj.getNum()<<endl;
   cout<<obj.getCh()<<endl;
   return 0;
}

OUTPUT

100
A

C++ Abstract Classes

C++ class is made abstract by declaring one of its functions as <> vital>pure virtual function. A pure virtual function is mentioned by placing “= 0” in its declaration. Derived classes must provide their implementation.

EXAMPLE

#include <iostream>  
using namespace std;  
 class Shape    
{    
    public:   
    virtual void draw()=0;    
};    
 class Rectangle : Shape    
{    
    public:  
     void draw()    
    {    
        cout < <"drawing rectangle" < <endl;    
    }    
};    
class Circle: Shape    
{    
    public:  
     void draw()    
    {    
        cout <<"drawing circle" < <endl;    
    }    
};    
int main( ) {  
    Rectangle rec;  
    Circle cir;  
    rec.draw();    
    cir.draw();   
   return 0;  
}  

OUTPUT

drawing rectangle
drawing circle

 C++ Files and Streams

S.NoData Type Description
1ofstreamIt represents the output file stream and it is used to create files and to write information to the files.
2ifstreamIt represents the input file stream and it is used to read information from the files.
3fstreamIt represents the file stream generally and has the ability of both ofstream and ifstream.

Opening a File

A file should be opened before you can read it or write to it. Either fstream or ofstream object may be used to open a file for writing. An ifstream object is used to open the file for reading purposes only.

S.NoMode Flag Description
1ios::ateAll output to the file to be appended at the end.
2ios::appIt opens a file for output and moves the read or write control to the end of the file.
3ios::truncIf the file already exists, the content will be truncated before opening the file.
4ios::outIt opens a file for writing.
5ios::inIt opens a file for reading.

SYNTAX

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );

Closing a File

When a C++ program is terminated it automatically flush all the streams, release all the allocated memory and close all the files that are opened.

SYNTAX

void close();

Reading from a File

You can read information from a file into your program using the stream extraction operator (>>). The only difference is that you use an fstream or ifstream object instead of the cin object.

READ AND WRITE EXAMPLE

#include <fstream>
#include <iostream>
using namespace std;
int main () 
{
   char data[100];
   ofstream outfile;
   outfile.open("afile.dat");
   cout << "Write in the file" << endl;
   cout << "Enter name: "; 
   cin.getline(data, 100);
   outfile << data << endl;
   cout << "Enter age: "; 
   cin >> data;
   cin.ignore();
   outfile << data << endl;
   outfile.close();
   ifstream infile; 
   infile.open("afile.dat"); 
   cout << "Read from the file" << endl; 
   infile >> data; 
   cout << data << endl;
   infile >> data; 
   cout << data << endl; 
   infile.close();
   return 0;
}

OUTPUT

$./a.out
Write in the file
Enter name: Zara
Enter age: 9
Read from the file
Zara
9

File Position Pointers

Both ostream and istream provide member functions for repositioning the file-position pointer. These member functions are seekp for ostream and seekg for istream. The argument to seekp and seekg is a long integer. A second argument can be mentioned to indicate the seek direction.

C++ Exception Handling

Exception Handling in C++ is a process to handle the runtime errors. You perform exception handling so the normal flow of the application can be maintained even after runtime errors.

In C++, an exception is an event or object which is thrown at runtime. All the exceptions are derived from std::exception class. If we don’t handle the exception, it prints the exception message and terminates the program.

ExceptionsDescriptions
std::bad_exceptionIt is used to handle unexpected exceptions.
std::logic_failureIt can be detected by reading a code.
std::bad_typeidIt is generally be thrown by typeid.
std::runtime_errorIt cannot be detected by reading a code.
std::exceptionIt is an exception and parent class of all the standard C++ exceptions.
std::bad_castIt is generally be thrown by dynamic_cast.
std::bad_allocIt is generally be thrown by new.

 C++ exception handling is based upon three keywords: try, catch, and throw.

  • try −  try block identifies a block of code for which a particular exception will be activated. One or more catch blocks follow it.
  • catch − A program catches an exception through an exception handler. The catch keyword shows the catching of an exception.
  • throw − A program throws the exception when a problem shows up. This is done using a throw keyword.

EXAMPLE

#include <iostream>  
using namespace std;  
float division(int x, int y) 
{  
   if( y == 0 ) 
  {  
      throw "Attempted to divide by zero!";  
   }  
   return (x/y);  
}  
int main () 
{  
   int i = 25;  
   int j = 0;  
   float k = 0;  
   try 
    {  
      k = division(i, j);  
      cout << k << endl;  
     }
        catch (const char* e) 
   {  
         cerr << e << endl;  
   } 
   return 0;  
} 

C++ Dynamic Memory

Memory is divided into two parts −

  • The stack − All the variables declared inside the function takes up a memory from the stack.
  • The heap − This is unused memory of the program, and it is used to allocate the memory dynamically when the program runs.

Programmers can allocate storage space dynamically while the program is running. Still, programmers cannot create new variable names, and for this reason, dynamic allocation requires two criteria:

  • Creating a dynamic space in memory
  • Storing its address in a pointer 

Memory de-allocation is a part of this concept too where the “clean-up” of space is done for other data storage. For de-allocating dynamic memory, you can use the delete operator. So, dynamic memory allocation refers to performing memory management for dynamic memory allocation manually.

new and delete Operators

Here, data-type might be any built-in data type that includes an array, or user-defined data types have class or structure. Let us start with built-in data types

SYNTAX

new data-type;

When you feel a variable that is not dynamically allocated and is not anymore required, you can free up the memory in the free store with the ‘delete’ operator.

SYNTAX

delete pvalue;

EXAMPLE

#include <iostream>
using namespace std;
int main () 
{
   double* pvalue  = NULL; 
   pvalue  = new double;  
   *pvalue = 29494.99;     
   cout << "Value of pvalue : " << *pvalue << endl;
   delete pvalue;         
   return 0;
}

Dynamic memory allocation of arrays

If you as a programmer; want to allocate memory for an array of characters with the help of the same syntax you can do that.

EXAMPLE

#include <iostream>
using namespace std;
class Box 
{
   public:
      Box() 
  { 
         cout << "Constructor called!" <<endl; 
  }
      ~Box() 
  { 
         cout << "Destructor called!" <<endl; 
   }
};
int main() 
{
   Box* myBoxArray = new Box[4];
   delete [] myBoxArray; 
   return 0;
}

Namespaces offer you to group named entities that have global scope into narrower scopes, giving them namespace scope. This also allows organizing the elements of programs into different logical scopes referred to by names. A namespace is a feature present in C++ and not present in C. Multiple namespace blocks with the same name are allowed. All declarations within the blocks are declared in the named scope.

SYNTAX

namespace namespace_name 
{
   int x, y
}

EXAMPLE

#include <iostream> 
using namespace std; 
namespace ns1 
{ 
    int value()   { return 5; } 
} 
namespace ns2 
{ 
    const double x = 100; 
    double value() { return 2*x; } 
} 
int main() 
{  
    cout << ns1::value() << '\n'; 
    cout << ns2::value() << '\n'; 
    cout << ns2::x << '\n';       
    return 0; 
}

OUTPUT

5
200
100

Discontiguous Namespaces

A namespace is defined in several parts and a namespace is made up of the sum of its defined parts. The separate parts of the namespace are spread over multiple files.

SYNTAX

namespace namespace_name 
{
}

Nested Namespaces

Here you can define one namespace inside another name space

SYNTAX

namespace namespace_name1 
{
   namespace namespace_name2 
{
}
}

EXAMPLE

#include <iostream>
using namespace std;
namespace first_space {
   void func() 
{
      cout << "Inside first_space" << endl;
   }
   namespace second_space 
{
      void func() 
      {
         cout << "Inside second_space" << endl;
      }
   }
}
using namespace first_space::second_space;
int main () 
{
   func();
   return 0;
}

C++ Templates

The template is a feature of C++ which offers you to write generic programs. In other terms, you can create a single function or a class to work with different data types using templates. Templates are used in the larger codebase for code flexibility and reusability of the programs.

These concepts are used in two ways:

  • Function Templates
  • Class Templates

Function templates

A function template works just like a normal function, with one key difference.

A single function template may work with different data types, but, a single normal function may work with one set of data types.

Typically, if you want to perform identical operations on multiple types of data, you can use function overloading to create functions with the function declaration.

Although, a better approach would be to use function templates because you can perform the same task writing less and maintainable code.

EXAMPLE

#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b) 
{ 
   return a < b ? b:a; 
}
int main () 
{
   int i = 40;
   int j = 20;
   cout << "Max(i, j): " << Max(i, j) << endl; 
   double f1 = 13.5; 
   double f2 = 20.8; 
   cout << "Max(f1, f2): " << Max(f1, f2) << endl; 
   string s1 = "Hello"; 
   string s2 = "World"; 
   cout << "Max(s1, s2): " << Max(s1, s2) << endl; 
   return 0;
}

OUTPUT

Max(i, j): 40
Max(f1, f2): 20.8
Max(s1, s2): World

Class templates

Like the function templates, you can create class templates for class operations. Usually, you would need to create a different class for each data type OR create other member variables and functions within the single class.

This will unnecessarily bloat your codebase and will be hard to maintain, as a change in one class/function must be performed on all classes/functions. Although class templates make it easy to reuse the same code for all data types.

EXAMPLE

#include <iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
T add() { return num1 + num2; }
T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() { return num1 / num2; }
};
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
cout << "Int results:" << endl;
intCalc.displayResult();
cout << endl << "Float results:" << endl;
floatCalc.displayResult();
return 0;
}

OUTPUT

Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2

C++ Preprocessors

Preprocessor directives are the lines included in the code of programs preceded by a hash sign (#). These lines are not programmed statements but directives for the preprocessor. The preprocessor examines the code before the compilation of code begins and resolves all the directives before regular statements generate any code.

The preprocessor directives extend across a single line of code. As soon as the newline character is found, the preprocessor directive is ended.

There are 4 main types of preprocessor directives:

  • Macros
  • File Inclusion
  • Conditional Compilation
  • Other directives

Macros

Macros are a piece of code which is given some name. Whenever the compiler encounters this name, it replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro. 

EXAMPLE

#define LIMIT 5 
int main() 
{ 
    for (int i = 0; i < LIMIT; i++) 
   { 
        std::cout << i << "\n"; 
    } 
    return 0; 
} 

OUTPUT

0
1
2
3
4

Predefined C++ macros

  • __LINE__

It contains the line number of the program when the program being compiled.

  • __FILE__

It contains the current filename of the program when it is being compiled.

  • __DATE__

It contains the string that is the date of the translation of the source file into object code.

  • __TIME__

It contains a string of hour:minute: second that is the time at which the program was compiled.

File inclusion

This preprocessor directive tells the compiler to include a file in the program. There are two types of files which are retained by the user in the program:

  • Header File or Standard files: These files contain the definition of pre-defined functions such as printf(), scanf() etc. These files should be included for working with these functions. A different function is declared in separate header files.
  • User-defined files: When a program becomes tremendous, it is good practice to divide it into smaller files and include whenever needed. These types of files are user-defined files. 

Conditional Compilation

It helps to compile a specific portion of the program or to skip compilation of some particular part of the program based on some conditions. 

SYNTAX

#ifdef macro_name
    statement1;
    statement2;
    statement3;
    .
    .
    .
    statementN;
#endif

Other directives

Apart from the directives mentioned above here are two more directives which are not commonly used. These are:

  • #undef Directive: The #undef directive is used to undefine an existing macro.
  • #pragma Directive: It is a special purpose directive, and it is used to turn on or off some features.

C++ Signal handling

Signals are the interruptions that the operating system provides to a process that will end a programme prematurely. By pressing Ctrl+C on a UNIX, LINUX, Mac OS X or Windows machine, you can create interrupts. 

There are signals that the software cannot detect, but there is a list of signals that you can catch in your programme and take acceptable signal-based actions. The C++ header file <csignal> describes these signals.

S.NoSignal Description
1SIGFPEAn erroneous arithmetic operation, such as a zero break or an overflow operation. 
2SIGABRTAbnormal programme termination, such as a call to abort. 
3SIGINTReceipt of a signal of interactive focus 
4SIGILLDiscovery of an illegitimate instruction. 
5SIGTERMSubmitted a termination request to the programme.
6SIGSEGVInvalid Disk Access. 

The signal() Function

The C++ signal handling library includes a signal feature to trap unpredictable events.

SYNTAX

void (*signal (int sig, void (*func)(int)))(int); 

EXAMPLE

#include <iostream>
#include <csignal>
using namespace std;
void signalHandler( int signum ) 
{
   cout << "Interrupt signal (" << signum << ") received.\n";
   exit(signum);  
}
int main () 
{
   signal(SIGINT, signalHandler);  
   while(1) {
      cout << "Going to sleep.." << endl;
      sleep(1);
   }
   return 0;
}

OUTPUT

Going to sleep..
Going to sleep..
Going to sleep..

The raise() Function

With the raise() function, which takes an integer signal number as an argument, you can produce signals.

SYNTAX

int raise (signal sig);

EXAMPLE

#include <iostream>
#include <csignal>
using namespace std;
void signalHandler( int signum )
{
   cout << "Interrupt signal (" << signum << ") received.\n";
   exit(signum);  
}
int main () 
{
   int i = 0; 
   signal(SIGINT, signalHandler);  
   while(++i) 
  {
      cout << "Going to sleep.." << endl;
      if( i == 3 ) 
     {
         raise( SIGINT);
      }
      sleep(1);
   }
   return 0;
}

OUTPUT

Going to sleep..
Going to sleep..
Going to sleep..
Interrupt signal (2) received.

Multithreading is a specialised type of multitasking and the function that enables your machine to run two or more programmes simultaneously is a multitasking function. There are two types of multitasking in general: process-based and thread-based. The parallel execution of programmes is handled by process-based multitasking. Multitasking based on threads deals with the parallel execution of portions of the same programme. There are two or three components of a multithreaded programme that will run simultaneously.

SYNTAX

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
S.NOParameterDescription
1argA single statement that can be forwarded to routine-start. It must be transferred as a pointer cast of type void by comparison. NULL can be used when there is no argument to move.
2threadAn opaque, special identifier for the current thread that the subroutine returns. 
3attrAn invisible object attribute that can be used for setting thread attributes. You may define an object with thread properties, or NULL with the default values. 
4start_routineThe C++ routine that once established, the thread will execute. 

Threads Terminating 

We use the following routine to terminate a POSIX thread:

#include <pthread.h>
pthread_exit (status)

Here, pthread exit is used to exit a thread directly. Usually, once a thread has finished its job and is no longer needed to function, the pthread exit() routine is named. 

If main() terminates and exits with pthread exit() before the threads it produces, the other threads can begin to run. Otherwise as main() ends, they are immediately terminated

Threads Entering and Detaching 

Two routines we can use to enter or remove threads are followed. 

pthread_join (threadid, status) 
pthread_detach (threadid)

The subroutine pthread join() blocks the calling thread until the ‘threadid’ thread is terminated. One of its attributes determines whether it is joinable or detached when a thread is formed. It can only be joined by threads that are generated as joinable. It can never be joined if a thread is formed as detached.

C++ Web Programming

And what is CGI? 

A collection of guidelines that describe how information is shared between the web server and a custom script is the Typical Gateway Interface or CGI. For external gateway systems, the Generic Gateway Interface, or CGI, is a standard for interfacing with information servers such as HTTP servers. CGI/1.1 is the latest version, and CGI/1.2 is in development.

Browsing on the Internet 

Let’s see what happens when we press a hyperlink to browse a certain web page or URL in order to grasp the concept of CGI. The HTTP web server is contacted by your browser and demands the URL, i.e. Filename by filename. The web server parses the URL and looks for a filename. If the requested file is located, the web server will transfer the file back to the browser, otherwise, it will send an error message saying you have requested an invalid file.

The Popular Gateway Interface (CGI) is a basic protocol that allows applications to communicate with Web servers and with clients. It is possible to write these CGI programmes in Python, PERL, Shell, C or C++, etc.

EXAMPLE

#include <iostream>
using namespace std;
int main () 
{
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Hello World - First CGI Program</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<h2>Hello World! </h2>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   return 0;
}

Webserver configuration

Make sure that the webserver accepts CGI before continuing with CGI programming and it is designed to accommodate CGI programmes. Many of the CGI programmes that the HTTP server runs are located in a pre-configured directory. This directory is called a CGI directory and it is named /var/www/cgi-bin by convention. CGI files will have extensions as .cgi by convention, although they are executable with C++.

HTTP headers

  • Set-Cookie: String

Configure the cookie that passes through the string. 

  • Last-modified: Date 

The date of the resource’s last update.

  • Content-length: N

The length, in bytes, of the returned data. In order to report the approximate loading time for a file, the browser uses this value.

  • Content-type:

A MIME string that specifies the format of the string

  • Location: URL

The URL that should be returned, rather than the requested URL. This file will be used to redirect a request to another file.

  • Expires: Date 

The day when the data became useless. The browser should use this to decide whether a website has to be refreshed. 

Environment variables

  • CONTENT TYPE: The sort of content data that is used when the client sends the attached content to the server. For eg, uploading files, etc. 
  • CONTENT LENGTH: Duration of questionnaire information that can only be obtained for POST requests.
  • HTTP-COOKIE: Returns the cookies set in key & value pair type. 
  • AGENT HTTP USER: The request-header User-Agent field provides information about the user agent that initiated the request. It is the name of a browser on the internet. 
  • PATH INFO: The direction to the CGI script file.
  • QUERY STRING: URL-encoded information that is submitted with a request from the GET process.
  • REMOTE ADDRR: The remote host’s IP address that allows the appeal. This may be helpful for logging or for purposes of authentication. 
  • REMOTE HOST: The fully qualified name of the seeking host. If this information is not available, it is possible to use REMOTE ADDR to get an IR address. 
  • REQUEST METHOD: The methodology used for producing the submission. GET and POST are the most popular approaches. 
  • SCRIPT FILENAME: The complete road to a CGI script
  • SERVER_NAME: The domain name or IP address of the server. 
  • SERVER_SOFTWARE: The program name and version that the server is running.

GET and POST Methods

When you try to transfer any details from your browser to the webserver and eventually to your CGI application, you need to come across certain scenarios. Two approaches are used most commonly by the browser to transfer this information to the webserver. Those approaches are the GET method and the POST method.

URL EXAMPLE GET Method

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 
#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>  
using namespace std;
using namespace cgicc;
int main () 
{
   Cgicc formData;
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Using GET and POST Methods</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   form_iterator fi = formData.getElement("first_name");  
   if( !fi->isEmpty() && fi != (*formData).end()) 
  {  
      cout << "First name: " << **fi << endl;  
   } else 
  {
      cout << "No text entered for first name" << endl;  
   }
   cout << "<br/>\n";
   fi = formData.getElement("last_name");  
   if( !fi->isEmpty() &&fi != (*formData).end()) 
  {  
      cout << "Last name: " << **fi << endl;  
   } else 
  {
      cout << "No text entered for last name" << endl;  
   }
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   return 0;
}

Using cookies

The HTTP protocol is a protocol that is stateless. But it is important for a commercial website to retain session data between various sites. One user registration, for example, ends after several pages have been completed. But how to hold session details for the user across all web sites. The most reliable way to remember and monitor interests, sales, commissions, and other details needed for improved visitor experience or site statistics is to use cookies in certain cases.

In the form of a cookie, your server transfers some data to the visitor’s window. The cookie will be approved by the browser. If it does, it’s saved on the visitor’s hard drive as a plain text archive. Now the cookie is ready for recovery when the user hits another page on your web. When recovered, what was stored is known/remembered by the server. 

  • Expires-This means the expiry date of the cookie. If this is blank, as the visitor quits the browser, the cookie will expire. 
  • Domain − This displays the site’s domain name. 
  • Path − This indicates the path to the cookie-setting directory or web page. If you try to grab a cookie from some directory or tab, it can be null. 
  • Secure − If this field includes the word “secure” then only a secure server can recover the cookie. If this field is blank, no other restriction applies.
  • Name = value − In the form of key and value pairs, cookies are set and retrieved.

Example File upload

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 
#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main () 
{
   Cgicc cgi;
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>File Upload in CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   const_file_iterator file = cgi.getFile("userfile");
   if(file != cgi.getFiles().end()) 
   {
      cout << HTTPContentHeader(file->getDataType());
      file->writeToStream(cout);
    }
   cout << "<File uploaded successfully>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   return 0;
}

Conclusion

With this we come to the end of this C++ tutorial. Hope this helped you to understand the basics about C++ programming.

Recommended Articles