Full C++

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 123
At a glance
Powered by AI
The key takeaways are that C++ provides file stream capabilities through the fstream library to read from and write to files. The main data types used are fstream, ifstream, and ofstream.

The main data types used for file streams in C++ are: fstream, which can be used to create, write to, and read from files; ifstream, which is used to read from files; and ofstream, which is used to create and write to files.

The steps to write data to a file in C++ are: 1) Include the fstream header, 2) Create an ofstream object and open the file, 3) Write to the file using insertion operator, 4) Close the file when done.

C++

Introduction
C++ Tutorial

C++ tutorial provides basic and advanced concepts of C++. Our C++ tutorial is designed
for beginners and professionals.

C++ is an object-oriented programming language. It is an extension to C programming.

Our C++ tutorial includes all topics of C++ such as first example, control statements,
objects and classes, inheritance, constructor, destructor, this, static, polymorphism,
abstraction, abstract class, interface, namespace, encapsulation, arrays, strings, exception
handling, File IO, etc.

C++ Program with Online C++ Compiler


In this tutorial, all C++ programs are given with C++ compiler so that you can easily
change the C++ program code.

File: main.cpp

1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.    cout << "Hello C++ Programming";  
5.    return 0;  
6. }  
What is C++
C++ is a general purpose, case-sensitive, free-form programming language that supports
object-oriented, procedural and generic programming.

C++ is a middle-level language, as it encapsulates both high and low level language
features.

Object-Oriented Programming (OOPs)


C++ supports the object-oriented programming, the four major pillar of object oriented
programming used in C++ are:

1. Inheritance

2. Polymorphism

3. Encapsulation

4. Abstraction

Standard Libraries
Standard C++ programming is divided into three important parts:

o The core library includes the data types, variables and literals, etc.

o The standard library includes the set of functions manipulating strings, files, etc.

o The Standard Template Library (STL) includes the set of methods manipulating a
data structure.

Usage of C++
By the help of C++ programming language, we can develop different types of secured and
robust applications:

o Window application

o Client-Server application

o Device drivers

o Embedded firmware etc


C vs C++
No. C C++

1) C follows the procedural style C++ is multi-paradigm. It supports


programming. both procedural and object oriented.

2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
outside users.

3) C follows the top-down C++ follows the bottom-up approach.


approach.

4) C does not support function C++ supports function overloading.


overloading.

5) In C, you can't use functions in In C++, you can use functions in


structure. structure.

6) C does not support reference C++ supports reference variables.


variables.

7) In C, scanf() and printf() are C++ mainly uses stream cin and


mainly used for input/output. cout to perform input and output
operations.

8) Operator overloading is not Operator overloading is possible in C++.


possible in C.

9) C programs are divided C++ programs are divided


into procedures and modules into functions and classes.

10 C does not provide the feature of C++ supports the feature of namespace.
) namespace.

11 Exception handling is not easy in C. C++ provides exception handling using


) It has to perform using other Try and Catch block.
functions.
C++ history
History of C++ language is interesting to know. Here we are going to discuss brief history
of C++ language.

C++ programming language was developed in 1980 by Bjarne Stroustrup at bell


laboratories of AT&T (American Telephone & Telegraph), located in U.S.A.

Bjarne Stroustrup is known as the founder of C++ language.

It was develop for adding a feature of OOP (Object Oriented Programming) in C without
significantly changing the C component.

C++ programming is "relative" (called a superset) of C, it means any valid C program is


also a valid C++ program.

Let's see the programming languages that were developed before C++ language.

Language Year Developed By

Algol 196 International Group


0

BCPL 196 Martin Richard


7

B 197 Ken Thompson


0

Traditional 197 Dennis Ritchie


C 2

K&RC 197 Kernighan & Dennis Ritchie


8

C++ 198 Bjarne Stroustrup


0
C++ Features
C++ is object oriented programming language. It provides a lot of features that are given
below.

1. Simple

2. Machine Independent or Portable

3. Mid-level programming language

4. Structured programming language

5. Rich Library

6. Memory Management

7. Fast Speed

8. Pointers

9. Recursion
10. Extensible

11. Object Oriented

12. Compiler based

1) Simple
C++ is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed in many machines with little bit or
no change. But it is not platform-independent.

3) Mid-level programming language


C++ is also used to do low level programming. It is used to develop system applications
such as kernel, driver etc. It also supports the feature of high level language. That is why it
is known as mid-level language.

4) Structured programming language


C++ is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify.

5) Rich Library
C++ provides a lot of inbuilt functions that makes the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C++ language, we can free the
allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C++ language is fast.

8) Pointer
C++ provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array etc.
9) Recursion
In C++, we can call the function within the function. It provides code reusability for every
function.

10) Extensible
C++ language is extensible because it can easily adopt new features.

11) Object Oriented


C++ is object oriented programming language. OOPs makes development and maintenance
easier where as in Procedure-oriented programming language it is not easy to manage if
code grows as project size grows.

12) Compiler based


C++ is a compiler based programming language, it means without compilation no C++
program can be executed. First we need to compile our program using compiler and then
we can execute our program.

C++ Program
Before starting the abcd of C++ language, you need to learn how to write, compile and run
the first C++ program.

To write the first C++ program, open the C++ console and write the following code:

1. #include <iostream.h>  
2. #include<conio.h>  
3. void main() {  
4.    clrscr();  
5.    cout << "Welcome to C++ Programming.";   
6.    getch();  
7. }  

#include<iostream.h> includes the standard input output library functions. It


provides cin and cout methods for reading from input and writing to output respectively.

#include includes the console input output library functions. The getch() function is


defined in conio.h file.

void main() The main() function is the entry point of every program in C++


language. The void keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to
C++ Programming." on the console.

getch() The getch() function asks for a single character. Until you press any key, it
blocks the screen.

How to compile and run the C++ program


There are 2 ways to compile and run the C++ program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c++ program.

Then click on the run menu then run sub menu to run the c++ program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.


You can view the use

C++ Program
Before starting the abcd of C++ language, you need to learn how to write, compile and run
the first C++ program.

To write the first C++ program, open the C++ console and write the following code:

1. #include <iostream.h>  
2. #include<conio.h>  
3. void main() {  
4.    clrscr();  
5.    cout << "Welcome to C++ Programming.";   
6.    getch();  
7. }  

#include<iostream.h> includes the standard input output library functions. It


provides cin and cout methods for reading from input and writing to output respectively.

#include includes the console input output library functions. The getch() function is


defined in conio.h file.

void main() The main() function is the entry point of every program in C++


language. The void keyword specifies that it returns no value.

cout << "Welcome to C++ Programming." is used to print the data "Welcome to


C++ Programming." on the console.

getch() The getch() function asks for a single character. Until you press any key, it
blocks the screen.
How to compile and run the C++ program
There are 2 ways to compile and run the C++ program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c++ program.

Then click on the run menu then run sub menu to run the c++ program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.


You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

r screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

C++ Basic Input/Output


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

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

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

I/O Library Header Files


Let us see the common header files used in C++ programming are:

Header File Function and Description

<iostream It is used to define the cout, cin and cerr objects, which correspond to


> standard output stream, standard input stream and standard error
stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such
as setprecision and setw.
<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)


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

Let's see the simple example of standard output stream (cout):

1. #include <iostream>  
2. using namespace std;  
3. int main( ) {  
4.    char ary[] = "Welcome to C++ tutorial";  
5.    cout << "Value of ary is: " << ary << endl;  
6. }  

Output:

Value of ary is: Welcome to C++ tutorial

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the standard input
device, which is usually a keyboard. The cin is used in conjunction with stream extraction
operator (>>) to read the input from a console.

Let's see the simple example of standard input stream (cin):

1. #include <iostream>  
2. using namespace std;  
3. int main( ) {  
4.   int age;  
5.    cout << "Enter your age: ";  
6.    cin >> age;  
7.    cout << "Your age is: " << age << endl;  
8. }  

Output:
Enter your age: 22
Your age is: 22

Standard end line (endl)


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

Let's see the simple example of standard end line (endl):

1. #include <iostream>  
2. using namespace std;  
3. int main( ) {  
4. cout << "C++ Tutorial";     
5. cout << " Javatpoint"<<endl;   
6. cout << "End of line"<<endl;   
7. }   

Output:

C++ Tutorial Javatpoint


End of line
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:

1. type variable_list;   

The example of declaring variable is given below:

1. int x;    
2. float y;    
3. char z;    

Here, x, y, z are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

1. int x=5,b=10;  //declaring 2 variable of integer type    
2. float f=30.8;    
3. char c='A';    

Rules for defining variables


A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start with digit.

No white space is allowed within variable name.

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

Valid variable names:

1. int a;    
2. int _ab;    
3. int a30;    
Invalid variable names:

int 4;    int x y;    int double;  

C++ Data Types


A data type specifies the type of data that a variable can store such as integer, floating,
character etc.

There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

Basic Data Types


The basic data types are integer-based and floating-point based. C++ language supports
both signed and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating
system.

Let's see the basic data types. It size is given according to 32 bit OS.
Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 32,767

int 2 byte -32,768 to 32,767

signed int 2 byte -32,768 to 32,767

unsigned int 2 byte 0 to 32,767

short int 2 byte -32,768 to 32,767

signed short int 2 byte -32,768 to 32,767

unsigned short int 2 byte 0 to 32,767

long int 4 byte

signed long int 4 byte

unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 byte


C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A
list of 32 Keywords in C++ Language which are also available in C language are
given below.

auto break case char const continue default do

double else enum exter float for goto if


n

int long registe return short signed sizeof static


r

struct switch typedef union unsigne void volatile while


d

A list of 30 Keywords in C++ Language which are not available in C language are
given below.

asm dynamic_cas namespace reinterpret_cast bool


t

explicit new static_cast false catch

operato template friend private class


r

this inline public throw const_cast

delete mutable protected true try

typeid typename using virtual wchar_t


C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C


language.

o Arithmetic Operators

o Relational Operators

o Logical Operators

o Bitwise Operators

o Assignment Operator

o Unary operator

o Ternary or Conditional Operator

o Misc Operator
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and
next. The associativity specifies the operators direction to be evaluated, it may be left to
right or right to left.

Let's understand the precedence by the example given below:

int data=5+10*10;    

The "data" variable will contain 105 because * (multiplicative operator) is evaluated before
+ (additive operator).

The precedence and associativity of C++ operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicativ */% Left to right


e

Additive +- Right to left

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == !=/td> Right to left

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Right to left

Logical AND && Left to right


Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

C++
CONTROL STATEMENT
C++ if-else
In C++ programming, if statement is used to test the condition. There are various types of
if statements in C++.

o if statement

o if-else statement

o nested if statement

o if-else-if ladder

C++ IF Statement
The C++ if statement tests the condition. It is executed if condition is true.

1. if(condition){    
2. //code to be executed    
3. }  
C++ If Example
1. #include <iostream>  
2. using namespace std;  
3.    
4. int main () {  
5.    int num = 10;    
6.             if (num % 2 == 0)    
7.             {    
8.                 cout<<"It is even number";    
9.             }   
10.    return 0;  
11. }  

Output:/p>

It is even number

C++ IF-else Statement


The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.

1. if(condition){    
2. //code if condition is true    
3. }else{    
4. //code if condition is false    
5. }    

C++ If-else Example


1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.    int num = 11;    
5.             if (num % 2 == 0)    
6.             {    
7.                 cout<<"It is even number";    
8.             }   
9.             else  
10.             {    
11.                 cout<<"It is odd number";    
12.             }  
13.    return 0;  
14. }  

Output:
It is odd number

C++ If-else Example: with input from user


1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.     int num;  
5.     cout<<"Enter a Number: ";  
6.     cin>>num;  
7.             if (num % 2 == 0)    
8.             {    
9.                 cout<<"It is even number"<<endl;    
10.             }   
11.             else  
12.             {    
13.                 cout<<"It is odd number"<<endl;    
14.             }  
15.    return 0;  
16. }  

Output:

Enter a number:11
It is odd number

Output:

Enter a number:12
It is even number

C++ IF-else-if ladder Statement


The C++ if-else-if ladder statement executes one condition from multiple statements.

1. if(condition1){    
2. //code to be executed if condition1 is true    
3. }else if(condition2){    
4. //code to be executed if condition2 is true    
5. }    
6. else if(condition3){    
7. //code to be executed if condition3 is true    
8. }    
9. ...    
10. else{    
11. //code to be executed if all the conditions are false    
12. }    

C++ If else-if Example


1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.        int num;  
5.        cout<<"Enter a number to check grade:";    
6.        cin>>num;  
7.             if (num <0 || num >100)    
8.             {    
9.                 cout<<"wrong number";    
10.             }    
11.             else if(num >= 0 && num < 50){    
12.                 cout<<"Fail";    
13.             }    
14.             else if (num >= 50 && num < 60)    
15.             {    
16.                 cout<<"D Grade";    
17.             }    
18.             else if (num >= 60 && num < 70)    
19.             {    
20.                 cout<<"C Grade";    
21.             }    
22.             else if (num >= 70 && num < 80)    
23.             {    
24.                 cout<<"B Grade";    
25.             }    
26.             else if (num >= 80 && num < 90)    
27.             {    
28.                 cout<<"A Grade";    
29.             }    
30.             else if (num >= 90 && num <= 100)    
31.             {    
32.                 cout<<"A+ Grade";  
33.             }    
34.     }    

Output:

Enter a number to check grade:66


C Grade

Output:

Enter a number to check grade:-2


wrong number

C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C++.

1. switch(expression){      
2. case value1:      
3.  //code to be executed;      
4.  break;    
5. case value2:      
6.  //code to be executed;      
7.  break;    
8. ......      
9.       
10. default:       
11.  //code to be executed if all cases are not matched;      
12.  break;    
13. }    

C++ Switch Example


1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.        int num;  
5.        cout<<"Enter a number to check grade:";    
6.        cin>>num;  
7.            switch (num)    
8.           {    
9.               case 10: cout<<"It is 10"; break;    
10.               case 20: cout<<"It is 20"; break;    
11.               case 30: cout<<"It is 30"; break;    
12.               default: cout<<"Not 10, 20 or 30"; break;    
13.           }    
14.     }    
Output:

Enter a number:
10
It is 10

Output:

Enter a number:
55
Not 10, 20 or 30

C++ 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 same as C/C#. We can initialize variable, check condition and
increment/decrement value.

1. for(initialization; condition; incr/decr){    
2. //code to be executed    
3. }    

C++ For Loop Example


1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.          for(int i=1;i<=10;i++){      
5.             cout<<i <<"\n";      
6.           }       
7.     }   

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested For Loop


In C++, we can use for loop inside another for loop, it is known as nested for loop. The
inner loop is executed fully when outer loop is executed one time. So if outer loop and inner
loop are executed 4 times, inner loop will be executed 4 times for each outer loop i.e. total
16 times.

C++ Nested For Loop Example


Let's see a simple example of nested for loop in C++.

1. #include <iostream>  
2. using namespace std;  
3.    
4. int main () {  
5.         for(int i=1;i<=3;i++){      
6.              for(int j=1;j<=3;j++){      
7.             cout<<i<<" "<<j<<"\n";      
8.           }     
9.         }  
10.     }    

Output:

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

C++ Infinite For Loop


If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple
example of infinite for loop in C++.

1. #include <iostream>  
2. using namespace std;  
3.    
4. int main () {  
5.         for (; ;)    
6.           {    
7.                   cout<<"Infinitive For Loop";    
8.           }    
9.     }    

Output:

Infinitive For Loop


Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c

C++ 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 while loop than for loop.

1. while(condition){    
2. //code to be executed    
3. }    

Flowchart:

C++ While Loop Example


Let's see a simple example of while loop to print table of 1.
1. #include <iostream>  
2. using namespace std;  
3. int main() {         
4.  int i=1;      
5.          while(i<=10)   
6.        {      
7.             cout<<i <<"\n";    
8.             i++;  
9.           }       
10.     }  

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested While Loop Example


In C++, we can use while loop inside another while loop, it is known as nested while loop.
The nested while loop is executed fully when outer loop is executed once.

Let's see a simple example of nested while loop in C++ programming language.

1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.         int i=1;      
5.           while(i<=3)     
6.           {    
7.               int j = 1;    
8.               while (j <= 3)    
9. {      
10.             cout<<i<<" "<<j<<"\n";      
11.             j++;  
12.           }     
13.            i++;  
14.         }  
15.     }    

Output:

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

C++ Infinitive While Loop Example:


We can also create infinite while loop by passing true as the test condition.

1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.         while(true)  
5.           {    
6.                   cout<<"Infinitive While Loop";    
7.           }    
8.     }    

Output:
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c

C++ 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 have to execute the loop at least once, it is
recommended to use do-while loop.

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

1. do{    
2. //code to be executed    
3. }while(condition);  

Flowchart:

C++ do-while Loop Example


Let's see a simple example of C++ do-while loop to print the table of 1.

1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.      int i = 1;    
5.           do{    
6.               cout<<i<<"\n";    
7.               i++;    
8.           } while (i <= 10) ;    
9. }  

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested do-while Loop


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

Let's see a simple example of nested do-while loop in C++.

1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.      int i = 1;    
5.          do{    
6.               int j = 1;          
7.               do{    
8.                 cout<<i<<"\n";        
9.                   j++;    
10.               } while (j <= 3) ;    
11.               i++;    
12.           } while (i <= 3) ;     
13. }  

Output:

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

C++ Infinitive do-while Loop


In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.

1. do{    
2. //code to be executed    
3. }while(true);  

C++ Infinitive do-while Loop Example


1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.       do{    
5.               cout<<"Infinitive do-while Loop";    
6.           } while(true);     
7. }  

Output:

Infinitive do-while Loop


Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c

C++ Break Statement


The C++ break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.

1. jump-statement;      
2. break;  

Flowchart:

C++ Break Statement Example


Let's see a simple example of C++ break statement which is used inside the loop.

1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.       for (int i = 1; i <= 10; i++)    
5.           {    
6.               if (i == 5)    
7.               {    
8.                   break;    
9.               }    
10.         cout<<i<<"\n";    
11.           }    
12. }  

Output:

1
2
3
4

C++ Break Statement with Inner Loop


The C++ break statement breaks inner loop only if you use break statement inside the inner
loop.

Let's see the example code:

1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.     for(int i=1;i<=3;i++){        
6.             for(int j=1;j<=3;j++){        
7.                 if(i==2&&j==2){        
8.                     break;        
9.                         }        
10.                     cout<<i<<" "<<j<<"\n";             
11.                     }        
12.           }    
13. }  

Output:

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

C++ Continue Statement


The C++ continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.

1. jump-statement;      
2. continue;     

C++ Continue Statement Example


1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.      for(int i=1;i<=10;i++){      
6.             if(i==5){      
7.                 continue;      
8.             }      
9.             cout<<i<<"\n";      
10.         }        
11. }  

Output:

1
2
3
4
6
7
8
9
10

C++ Continue Statement with Inner Loop


C++ Continue Statement continues inner loop only if you use continue statement inside the
inner loop.
1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.  for(int i=1;i<=3;i++){        
6.             for(int j=1;j<=3;j++){        
7.              if(i==2&&j==2){        
8.                 continue;        
9.                         }        
10.                 cout<<i<<" "<<j<<"\n";                  
11.                     }        
12.             }            
13. }  

Output:

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

C++ Goto Statement


The C++ goto statement is also known as jump statement. It is used to transfer control to
the other part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from deeply nested loop or switch case label.

C++ Goto Statement Example


Let's see the simple example of goto statement in C++.

1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5. ineligible:    
6.          cout<<"You are not eligible to vote!\n";    
7.       cout<<"Enter your age:\n";    
8.       int age;  
9.       cin>>age;  
10.       if (age < 18){    
11.               goto ineligible;    
12.       }    
13.       else    
14.       {    
15.               cout<<"You are eligible to vote!";     
16.       }         
17. }  

Output:

You are not eligible to vote!


Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!

C++ Comments
The C++ comments are statements that are not executed by the compiler. The comments
in C++ programming can be used to provide explanation of the code, variable, method or
class. By the help of comments, you can hide the program code also.

There are two types of comments in C++.

o Single Line comment

o Multi Line comment

C++ Single Line Comment


C++ Multi Line Comment
The C++ multi line comment is used to comment multiple lines of code. It is surrounded by
slash and asterisk (/∗ ..... ∗/). Let's see an example of multi line comment in C++.

1. #include <ostream>  
2. using namespace std;  
3. int main()  
4. {  
5. /* declare and   
6. print variable in C++. */   
7.  int x = 35;     
8.  cout<<x<<"\n";    //this is single line coment     
9. }  

Output:

35
C++
FUNCTIONS

C++ Functions
The function in C++ language is also known as procedure or subroutine in other
programming languages.

To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.

Advantage of functions in C
There are many advantages of functions.
1) Code Reusability

By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number
or not. Without using function, you need to write the prime number logic 3 times. So,
there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it
several times.

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files
such as ceil(x), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++


programmer, so that he/she can use it many times. It reduces complexity of a big
program and optimizes the code.

Declaration of a function
The syntax of creating function in C++ language is given below:

1. return_type function_name(data_type parameter...)  
2. {    
3. //code to be executed    
4. }  
C++ Function Example
Let's see the simple example of C++ function.

1. #include <iostream>  
2. using namespace std;  
3. void func() {    
4.    static int i=0; //static variable    
5.    int j=0; //local variable    
6.    i++;    
7.    j++;    
8.    cout<<"i=" << i<<" and j=" <<j<<endl;    
9. }    
10. int main()  
11. {  
12.  func();    
13.  func();    
14.  func();    
15. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

Call by value and call by reference in C++


There are two ways to pass value or data to function in C language: call by value and
call by reference. Original value is not modified in call by value but it is modified in call
by reference.
Let's understand call by value and call by reference in C++ language one by one.

Call by value in C++


In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function
parameter in stack memory location. If you change the value of function parameter, it
is changed for the current function only. It will not change the value of variable inside
the caller method such as main().

Let's try to understand the concept of call by value in C++ language by the example
given below:

1. #include <iostream>  
2. using namespace std;  
3. void change(int data);  
4. int main()  
5. {  
6. int data = 3;  
7. change(data);  
8. cout << "Value of the data is: " << data<< endl;  
9. return 0;  
10. }  
11. void change(int data)  
12. {  
13. data = 5;  
14. }  

Output:

Value of the data is: 3

Call by reference in C++


In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments
share the same address space. Hence, value changed inside the function, is reflected
inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of
pointers.

Let's try to understand the concept of call by reference in C++ language by the
example given below:

1. #include<iostream>  
2. using namespace std;    
3. void swap(int *x, int *y)  
4. {  
5.  int swap;  
6.  swap=*x;  
7.  *x=*y;  
8.  *y=swap;  
9. }  
10. int main()   
11. {    
12.  int x=500, y=100;    
13.  swap(&x, &y);  // passing value to function  
14.  cout<<"Value of x is: "<<x<<endl;  
15.  cout<<"Value of y is: "<<y<<endl;  
16.  return 0;  
17. }    

Output:

Value of x is: 100


Value of y is: 500

Difference between call by value and call by


reference in C++

No Call by value Call by reference


.
1 A copy of value is passed to the An address of value is passed to the
function function

2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also

3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location

C++ Recursion
When function is called within the same function, it is known as recursion in C++. The
function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is known as
tail recursion. In tail recursion, we generally call the same function with return
statement.

Let's see a simple example of recursion.

1. recursionfunction(){    
2. recursionfunction(); //calling self function    
3. }    

C++ Recursion Example


Let's see an example to print factorial number using recursion in C++ language.

1. #include<iostream>  
2. using namespace std;    
3. int main()  
4. {  
5. int factorial(int);  
6. int fact,value;  
7. cout<<"Enter any number: ";  
8. cin>>value;  
9. fact=factorial(value);  
10. cout<<"Factorial of a number is: "<<fact<<endl;  
11. return 0;  
12. }  
13. int factorial(int n)  
14. {  
15. if(n<0)  
16. return(-1); /*Wrong value*/    
17. if(n==0)  
18. return(1);  /*Terminating condition*/  
19. else  
20. {  
21. return(n*factorial(n-1));      
22. }  
23. }  

Output:

Enter any number: 5


Factorial of a number is: 120

C++ Storage Classes


Storage class is used to define the lifetime and visibility of a variable and/or function
within a C++ program.

Lifetime refers to the period during which the variable remains active and visibility
refers to the module of a program in which the variable is accessible.

There are five types of storage classes, which can be used in a C++ program

1. Automatic
2. Register

3. Static

4. External

5. Mutable

Storage Class Keyword Lifetime Visibility Initial Value

Automatic auto Function Block Local Garbage

Register register Function Block Local Garbage

Mutable mutable Class Local Garbage

External extern Whole Program Global Zero

Static static Whole Program Local Zero

Automatic Storage Class


It is the default storage class for all local variables. The auto keyword is applied to all
local variables automatically.

1. {   
2. auto int y;  
3. float y = 3.45;  
4. }  

The above example defines two variables with a same storage class, auto can only be
used within functions.

Register Storage Class


The register variable allocates memory in register than RAM. Its size is same of register
size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.
Note: We can't get the address of register variable.

1. register int counter=0;    

Static Storage Class


The static variable is initialized only once and exists till the end of a program. It retains
its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

1. #include <iostream>  
2. using namespace std;  
3. void func() {    
4.    static int i=0; //static variable    
5.    int j=0; //local variable    
6.    i++;    
7.    j++;    
8.    cout<<"i=" << i<<" and j=" <<j<<endl;    
9. }    
10. int main()  
11. {  
12.  func();    
13.  func();    
14.  func();    
15. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

External Storage Class


The extern variable is visible to all the programs. It is used if two or more files are
sharing same variable or function.
1. extern int counter=0;    
C++
ARRAYS

C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements
that have contiguous memory location.

In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.
Advantages of C++ Array
o Code Optimization (less code)

o Random Access

o Easy to traverse data

o Easy to manipulate data

o Easy to sort data etc.

Disadvantages of C++ Array


o Fixed size

C++ Array Types


There are 2 types of arrays in C++ programming:

1. Single Dimensional Array

2.

3. Multidimensional Array

C++ Single Dimensional Array


Let's see a simple example of C++ array, where we are going to create, initialize and
traverse array.

1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.  int arr[5]={10, 0, 20, 0, 30};  //creating and initializing array    
6.         //traversing array    
7.         for (int i = 0; i < 5; i++)    
8.         {    
9.             cout<<arr[i]<<"\n";    
10.         }    
11. }  

Output:/p>

10
0
20
0
30

C++ Array Example: Traversal using foreach loop


We can also traverse the array elements using foreach loop. It returns array element one by
one.

1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.  int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array    
6.         //traversing array    
7.        for (int i: arr)     
8.         {    
9.             cout<<i<<"\n";    
10.         }    

C++ Passing Array to Function


In C++, to reuse the array logic, we can create function. To pass array to function in C++,
we need to provide only array name.

1. functionname(arrayname); //passing array to function    
C++ Passing Array to Function Example: print array
elements
Let's see an example of C++ function which prints the array elements.

1. #include <iostream>  
2. using namespace std;  
3. void printArray(int arr[5]);  
4. int main()  
5. {  
6.         int arr1[5] = { 10, 20, 30, 40, 50 };    
7.         int arr2[5] = { 5, 15, 25, 35, 45 };    
8.         printArray(arr1); //passing array to function    
9.         printArray(arr2);  
10. }  
11. void printArray(int arr[5])  
12. {  
13.     cout << "Printing array elements:"<< endl;  
14.     for (int i = 0; i < 5; i++)  
15.     {  
16.                    cout<<arr[i]<<"\n";    
17.     }  
18. }  

Output:

Printing array elements:


10
20
30
40
50
Printing array elements:
5
15
25
35
45

C++ Passing Array to Function Example: Print


minimum number
Let's see an example of C++ array which prints minimum number in an array using
function.

1. #include <iostream>  
2. using namespace std;  
3. void  printMin(int arr[5]);  
4. int main()  
5. {  
6.    int arr1[5] = { 30, 10, 20, 40, 50 };    
7.         int arr2[5] = { 5, 15, 25, 35, 45 };    
8.         printMin(arr1);//passing array to function    
9.          printMin(arr2);  
10. }  
11. void  printMin(int arr[5])  
12. {  
13.     int min = arr[0];    
14.         for (int i = 0; i > 5; i++)    
15.         {    
16.             if (min > arr[i])    
17.             {    
18.                 min = arr[i];    
19.             }    
20.         }    
21.         cout<< "Minimum element is: "<< min <<"\n";    
22. }  

Output:

Minimum element is: 10


Minimum element is: 5
C++ Passing Array to Function Example: Print
maximum number
Let's see an example of C++ array which prints maximum number in an array using
function.

1. #include <iostream>  
2. using namespace std;  
3. void  printMax(int arr[5]);  
4. int main()  
5. {  
6.         int arr1[5] = { 25, 10, 54, 15, 40 };    
7.         int arr2[5] = { 12, 23, 44, 67, 54 };    
8.         printMax(arr1); //Passing array to function  
9.          printMax(arr2);   
10. }  
11. void  printMax(int arr[5])  
12. {  
13.     int max = arr[0];    
14.         for (int i = 0; i < 5; i++)    
15.         {    
16.             if (max < arr[i])    
17.             {    
18.                 max = arr[i];    
19.             }    
20.         }    
21.         cout<< "Maximum element is: "<< max <<"\n";    
22. }  

Output:

Maximum element is: 54


Maximum element is: 67

C++ Multidimensional Arrays


The multidimensional array is also known as rectangular arrays in C++. It can be two
dimensional or three dimensional. The data is stored in tabular form (row ∗ column) which is
also known as matrix.
C++ Multidimensional Array Example
Let's see a simple example of multidimensional array in C++ which declares, initializes and
traverse two dimensional arrays.

1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.   int test[3][3];  //declaration of 2D array   
6.     test[0][0]=5;  //initialization   
7.     test[0][1]=10;   
8.     test[1][1]=15;  
9.     test[1][2]=20;  
10.     test[2][0]=30;  
11.     test[2][2]=10;  
12.     //traversal    
13.     for(int i = 0; i < 3; ++i)  
14.     {  
15.         for(int j = 0; j < 3; ++j)  
16.         {  
17.             cout<< test[i][j]<<" ";  
18.         }  
19.         cout<<"\n"; //new line at each row   
20.     }  
21.     return 0;  
22. }  

Output:

5 10 0
0 15 20
30 0 10

C++ Multidimensional Array Example: Declaration and


initialization at same time
Let's see a simple example of multidimensional array which initializes array at the time of
declaration.

1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.   int test[3][3] =  
6.     {  
7.         {2, 5, 5},  
8.         {4, 0, 3},  
9.         {9, 1, 8}  };  //declaration and initialization    
10.     //traversal    
11.     for(int i = 0; i < 3; ++i)  
12.     {  
13.         for(int j = 0; j < 3; ++j)  
14.         {  
15.             cout<< test[i][j]<<" ";  
16.         }  
17.         cout<<"\n"; //new line at each row   
18.     }  
19.     return 0;  
20. }  

Output:"

2 5 5
4 0 3
9 1 8
C++
POINTERS

C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator
that points to an address of a value.
Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer

There are many usage of pointers in C++ language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc()


functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It


reduces the code and improves the performance.

Symbols used in pointer


Symbol Name Description

& (ampersand Address operator Determine the address of a


sign) variable.

∗ (asterisk sign) Indirection Access the value of an address.


operator

Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).

1. int ∗   a; //pointer to int    
2. char ∗  c; //pointer to char    

Pointer Example
Let's see the simple example of using pointers printing the address and value.

1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5. int number=30;    
6. int ∗   p;      
7. p=&number;//stores the address of number variable    
8. cout<<"Address of number variable is:"<<&number<<endl;    
9. cout<<"Address of p variable is:"<<p<<endl;    
10. cout<<"Value of p variable is:"<<*p<<endl;    
11.    return 0;  
12. }  

Output
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
Value of p variable is:30

Pointer Program to swap 2 numbers without using


3rd variable
1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5. int a=20,b=10,∗p1=&a,∗p2=&b;    
6. cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;    
7. ∗p1=∗p1+∗p2;    
8. ∗p2=∗p1-∗p2;    
9. ∗p1=∗p1-∗p2;    
10. cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;    
11.    return 0;  
12. }  

Output

Before swap: ∗p1=20 ∗p2=10


After swap: ∗p1=10 ∗p2=20
C++
OOPS CONCEPTS
C++ OOPs Concepts
The major purpose of C++ programming is to introduce the concept of object
orientation to the C programming language.

Object Oriented Programming is a paradigm that provides many concepts such


as inheritance, data binding, polymorphism etc.

The programming paradigm where everything is represented as an object is known as


truly object-oriented programming language. Smalltalk is considered as the first truly
object-oriented programming language.

OOPs (Object Oriented Programming System)


Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing some
concepts:

o Object

o Class

o Inheritance

o Polymorphism

o Abstraction

o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.

Class
Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.

In C++, we use Function overloading and Function overriding to achieve polymorphism.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.

In C++, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
Advantage of OOPs over Procedure-oriented
programming language
1. OOPs makes development and maintenance easier where as in Procedure-
oriented programming language it is not easy to manage if code grows as project
size grows.

2. OOPs provide data hiding whereas in Procedure-oriented programming language


a global data can be accessed from anywhere.

3. OOPs provide ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming language.

C++ Object and Class


Since C++ is an object-oriented language, program is designed using objects and classes in C+
+.

C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.

In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through object.

Let's see an example to create object of student class using s1 as the reference variable.

1. Student s1;  //creating an object of Student      

In this example, Student is the type and s1 is the reference variable that refers to the instance of
Student class.
C++ Class
In C++, object is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.

Let's see an example of C++ class that has three fields only.

1. class Student    
2.  {    
3.      public:  
4.      int id;  //field or data member     
5.      float salary; //field or data member  
6.      String name;//field or data member    
7.  }    

C++ Object and Class Example


Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.

1. #include <iostream>  
2. using namespace std;  
3. class Student {  
4.    public:  
5.       int id;//data member (also instance variable)      
6.       string name;//data member(also instance variable)      
7. };  
8. int main() {  
9.     Student s1; //creating an object of Student   
10.     s1.id = 201;    
11.     s1.name = "Sonoo Jaiswal";   
12.     cout<<s1.id<<endl;  
13.     cout<<s1.name<<endl;  
14.     return 0;  
15. }  

Output:

201
Sonoo Jaiswal
C++ Class Example: Initialize and Display data through
method
Let's see another example of C++ class where we are initializing and displaying object through
method.

1. #include <iostream>  
2. using namespace std;  
3. class Student {  
4.    public:  
5.        int id;//data member (also instance variable)      
6.        string name;//data member(also instance variable)      
7.        void insert(int i, string n)    
8.         {    
9.             id = i;    
10.             name = n;    
11.         }    
12.        void display()    
13.         {    
14.             cout<<id<<"  "<<name<<endl;    
15.         }    
16. };  
17. int main(void) {  
18.     Student s1; //creating an object of Student   
19.     Student s2; //creating an object of Student  
20.     s1.insert(201, "Sonoo");    
21.     s2.insert(202, "Nakul");    
22.     s1.display();    
23.     s2.display();  
24.     return 0;  
25. }  

Output:

201 Sonoo
202 Nakul
C++ Class Example: Store and Display Employee
Information
Let's see another example of C++ class where we are storing and displaying employee
information using method.

1. #include <iostream>  
2. using namespace std;  
3. class Employee {  
4.    public:  
5.        int id;//data member (also instance variable)      
6.        string name;//data member(also instance variable)  
7.        float salary;  
8.        void insert(int i, string n, float s)    
9.         {    
10.             id = i;    
11.             name = n;    
12.             salary = s;  
13.         }    
14.        void display()    
15.         {    
16.             cout<<id<<"  "<<name<<"  "<<salary<<endl;    
17.         }    
18. };  
19. int main(void) {  
20.     Employee e1; //creating an object of Employee   
21.     Employee e2; //creating an object of Employee  
22.     e1.insert(201, "Sonoo",990000);    
23.     e2.insert(202, "Nakul", 29000);    
24.     e1.display();    
25.     e2.display();    
26.     return 0;  
27. }  

Output:

201 Sonoo 990000


202 Nakul 29000
C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally. The constructor in C+
+ has the same name as class or structure.

There can be two types of constructors in C++.

o Default constructor

o Parameterized constructor

C++ Default Constructor


A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object.

Let's see the simple example of C++ default Constructor.

1. #include <iostream>  
2. using namespace std;  
3. class Employee  
4.  {  
5.    public:  
6.         Employee()    
7.         {    
8.             cout<<"Default Constructor Invoked"<<endl;    
9.         }    
10. };  
11. int main(void)   
12. {  
13.     Employee e1; //creating an object of Employee   
14.     Employee e2;   
15.     return 0;  
16. }  

Output:

Default Constructor Invoked


Default Constructor Invoked
C++ Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide
different values to distinct objects.

Let's see the simple example of C++ Parameterized Constructor.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of
Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}

Output:

101 Sonoo 890000


102 Nakul 59000
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically.

A destructor is defined like constructor. It must have same name as class. But it is prefixed with
a tilde sign (~).

Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on
destructors.

C++ Constructor and Destructor Example.


#include <iostream>  
using namespace std;  
class Employee  
 {  
 public:  
       Employee()    
       {    
            cout<<"Constructor Invoked"<<endl;    
        }    
        ~Employee()    
        {    
            cout<<"Destructor Invoked"<<endl;    
        }  
};  
int main(void)   
{  
    Employee e1; //creating an object of Employee   
    Employee e2; //creating an object of Employee  
    return 0;  
}  

Output:

Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ this Pointer
In C++ programming, this is a keyword that refers to the current instance of the class. There
can be 3 main usage of this keyword in C++.

o It can be used to pass current object as a parameter to another method.

o It can be used to refer current class instance variable.

o It can be used to declare indexers.

C++ this Pointer Example


Let's see the example of this keyword in C++ that refers to the fields of current class.

#include <iostream>  
using namespace std;  
class Employee {  
  public:  
      int id; //data member (also instance variable)      
       string name; //data member(also instance variable)  
       float salary;  
       Employee(int id, string name, float salary)    
        {    
             this->id = id;    
            this->name = name;    
            this->salary = salary;   
        }    
       void display()    
        {    
            cout<<id<<"  "<<name<<"  "<<salary<<endl;    
        }    
};  
int main(void) {  
    Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee   
    Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee  
    e1.display();    
    e2.display();    
    return 0;  
}  
Output: 101 Sonoo 890000
102 Nakul 59000
C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C++, static can be field, method, constructor, class,
properties, operator and event.

Advantage of C++ static keyword


Memory efficient: Now we don't need to create instance for accessing the static members, so it
saves memory. Moreover, it belongs to the type, so it will not get memory each time when
instance is created.

C++ Static Field


A field which is declared as static is called static field. Unlike instance field which gets memory
each time whenever you create object, there is only one copy of static field created in the
memory. It is shared to all the objects.

It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.

C++ static field example


Let's see the simple example of static field in C++.

1. #include <iostream>  
2. using namespace std;  
3. class Account {  
4.    public:  
5.        int accno; //data member (also instance variable)      
6.        string name; //data member(also instance variable)  
7.        static float rateOfInterest;   
8.        Account(int accno, string name)   
9.         {    
10.              this->accno = accno;    
11.             this->name = name;    
12.         }    
13.        void display()    
14.         {    
15.             cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;   
16.         }    
17. };  
18. float Account::rateOfInterest=6.5;  
19. int main(void) {  
20.     Account a1 =Account(201, "Sanjay"); //creating an object of Employee   
21.     Account a2=Account(202, "Nakul"); //creating an object of Employee  
22.     a1.display();    
23.     a2.display();    
24.     return 0;  
25. }  

Output:

201 Sanjay 6.5


202 Nakul 6.5
C++ Structs
In C++, classes and structs are blueprints that are used to create instance of a class. Structs are
used for lightweight objects such as Rectangle, color, Point etc.

Unlike class, structs in C++ are value type than reference type. It is useful if you have data that
is not intended to be modified after creation of struct.

C++ Struct Example


Let's see a simple example of struct Rectangle which has two data members width and height.

1. #include <iostream>  
2. using namespace std;  
3.  struct Rectangle    
4. {    
5.    int width, height;    
6.     
7.  };    
8. int main(void) {  
9.     struct Rectangle rec;  
10.     rec.width=8;  
11.     rec.height=5;  
12.     cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;  
13.     return 0;  
14. }  

Output:

Area of Rectangle is: 40


C++ Struct Example: Using Constructor and Method
Let's see another example of struct where we are using constructor to initialize data and method
to calculate area of rectangle.

1. #include <iostream>  
2. using namespace std;  
3.  struct Rectangle    
4. {    
5.    int width, height;    
6.   Rectangle(int w, int h)    
7.     {    
8.         width = w;    
9.         height = h;    
10.     }    
11.   void areaOfRectangle() {     
12.     cout<<"Area of Rectangle is: "<<(width*height); }    
13.  };    
14. int main(void) {  
15.     struct Rectangle rec=Rectangle(4,6);  
16.     rec.areaOfRectangle();  
17.     return 0;  
18. }  

Output:

Area of Rectangle is: 24

C++ Enumeration
Enum in C++ is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum
constants are static and final implicitly.

C++ Enums can be thought of as classes that have fixed set of constants.
Points to remember for C++ Enum
o enum improves type safety

o enum can be easily used in switch

o enum can be traversed

o enum can have fields, constructors and methods

o enum may implement many interfaces but cannot extend any class because it internally
extends Enum class

C++ Enumeration Example


Let's see the simple example of enum data type used in C++ program.

1. #include <iostream>  
2. using namespace std;  
3. enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };  
4. int main()  
5. {  
6.     week day;  
7.     day = Friday;  
8.     cout << "Day: " << day+1<<endl;  
9.     return 0;  
10. }     

Output:

Day: 5

C++ friend function


If a function is defined as a friend function in C++ then the protected and private data of a class
can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.
Declaration of friend function in C++
1. class class_name  
2. {  
3.     friend data_type function_name(argument/s);  
4. };  

C++ friend function Example


Let's see the simple example of C++ friend function used to print the length of a box.

1. #include <iostream>  
2. using namespace std;  
3. class Box  
4. {  
5.     private:  
6.         int length;  
7.     public:  
8.         Box(): length(0) { }  
9.         friend int printLength(Box); //friend function  
10. };  
11. int printLength(Box b)  
12. {  
13.     b.length += 10;  
14.     return b.length;  
15. }  
16. int main()  
17. {  
18.     Box b;  
19.     cout<<"Length of box: "<< printLength(b)<<endl;  
20.     return 0;  
21. }  

Output:

Length of box: 10
C++
INHERTANCE
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or modify
the attributes and behaviors which are defined in other class.

In C++, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.

Advantage of C++ Inheritance


Code reusability: Now you can reuse the members of your parent class. So, there is no
need to define the member again. So less code is required in the class.

C++ Single Level Inheritance Example: Inheriting Fields


When one class inherits another class, it is known as single level inheritance. Let's see the
example of single level inheritance which inherits the fields only.

1. #include <iostream>  
2. using namespace std;  
3.  class Account {  
4.    public:  
5.    float salary = 60000;   
6.  };  
7.    class Programmer: public Account {  
8.    public:  
9.    float bonus = 5000;    
10.    };       
11. int main(void) {  
12.      Programmer p1;  
13.      cout<<"Salary: "<<p1.salary<<endl;    
14.      cout<<"Bonus: "<<p1.bonus<<endl;    
15.     return 0;  
16. }  
Output:

Salary: 60000
Bonus: 5000

In the above example, Employee is the base class and Programmer is the derived class.

C++ Single Level Inheritance Example: Inheriting


Methods
Let's see another example of inheritance in C++ which inherits methods only.

1. #include <iostream>  
2. using namespace std;  
3.  class Animal {  
4.    public:  
5.  void eat() {   
6.     cout<<"Eating..."<<endl;   
7.  }    
8.    };  
9.    class Dog: public Animal    
10.    {    
11.        public:  
12.      void bark(){  
13.     cout<<"Barking...";   
14.      }    
15.    };   
16. int main(void) {  
17.     Dog d1;  
18.     d1.eat();  
19.     d1.bark();  
20.     return 0;  
21. }  

Output:

Eating...
Barking...
C++ Multi Level Inheritance Example
When one class inherits another class which is further inherited by another class, it is known
as multi level inheritance in C++. Inheritance is transitive so the last derived class acquires
all the members of all its base classes.

1. #include <iostream>  
2. using namespace std;  
3.  class Animal {  
4.    public:  
5.  void eat() {   
6.     cout<<"Eating..."<<endl;   
7.  }    
8.    };  
9.    class Dog: public Animal   
10.    {    
11.        public:  
12.      void bark(){  
13.     cout<<"Barking..."<<endl;   
14.      }    
15.    };   
16.    class BabyDog: public Dog   
17.    {    
18.        public:  
19.      void weep() {  
20.     cout<<"Weeping...";   
21.      }    
22.    };   
23. int main(void) {  
24.     BabyDog d1;  
25.     d1.eat();  
26.     d1.bark();  
27.      d1.weep();  
28.      return 0;  
29. }  

30. Output:

Eating...Barking? Weeping?
C++ Aggregation (HAS-A Relationship)
In C++, aggregation is a process in which one class defines another class as any entity
reference. It is another way to reuse the class. It is a form of association that represents
HAS-A relationship.

C++ Aggregation Example


Let's see an example of aggregation where Employee class has the reference of Address
class as data member. In such way, it can reuse the members of Address class.

1. #include <iostream>  
2. using namespace std;  
3. class Address {  
4.     public:  
5.    string addressLine, city, state;    
6.      Address(string addressLine, string city, string state)    
7.     {    
8.         this->addressLine = addressLine;    
9.         this->city = city;    
10.         this->state = state;    
11.     }    
12. };  
13. class Employee    
14.     {    
15.         private:  
16.         Address* address;  //Employee HAS-A Address   
17.         public:  
18.         int id;    
19.         string name;    
20.         Employee(int id, string name, Address* address)    
21.        {    
22.            this->id = id;    
23.            this->name = name;    
24.            this->address = address;    
25.        }    
26.      void display()    
27.        {    
28.            cout<<id <<" "<<name<< " "<<     
29.              address->addressLine<< " "<< address->city<< " "<<address-
>state<<endl;    
30.        }    
31.    };   
32. int main(void) {  
33.     Address a1= Address("C-146, Sec-15","Noida","UP");    
34.     Employee e1 = Employee(101,"Nakul",&a1);    
35.             e1.display();   
36.    return 0;  
37. }  

Output:

101 Nakul C-146, Sec-15 Noida UP


C++
POLYMORPHISM
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means
many forms. It is a greek word. In object-oriented programming, we use 3 main
concepts: inheritance, encapsulation and polymorphism.

There are two types of polymorphism in C++:

o Compile time polymorphism: It is achieved by function overloading and


operator overloading which is also known as static binding or early binding.

o Runtime polymorphism: It is achieved by method overriding which is also


known as dynamic binding or late binding.

C++ Runtime Polymorphism Example


Let's see a simple example of runtime polymorphism in C++.

1. #include <iostream>  
2. using namespace std;  
3. class Animal {  
4.     public:  
5. void eat(){    
6. cout<<"Eating...";    
7.     }      
8. };   
9. class Dog: public Animal    
10. {    
11.  public:  
12.  void eat()    
13.     {    
14.        cout<<"Eating bread...";    
15.     }    
16. };  
17. int main(void) {  
18.    Dog d = Dog();    
19.    d.eat();  
20.    return 0;  
21. }  

Output:

Eating bread...

C++ Runtime Polymorphism Example: By using


two derived class
Let's see another example of runtime polymorphism in C++ where we are having
two derived classes.

1. #include <iostream>  
2. using namespace std;  
3. class Shape {  
4.     public:  
5. virtual void draw(){    
6. cout<<"drawing..."<<endl;    
7.     }      
8. };   
9. class Rectangle: public Shape    
10. {    
11.  public:  
12.  void draw()    
13.     {    
14.        cout<<"drawing rectangle..."<<endl;    
15.     }    
16. };  
17. class Circle: public Shape    
18. {    
19.  public:  
20.  void draw()    
21.     {    
22.        cout<<"drawing circle..."<<endl;    
23.     }    
24. };  
25. int main(void) {  
26.     Shape *s;  
27.     Shape sh;  
28.         Rectangle rec;  
29.         Circle cir;  
30.         s=&sh;  
31.      s->draw();   
32.         s=&rec;  
33.      s->draw();    
34.     s=○  
35.      s->draw();   
36. }  

Output:

drawing...
drawing rectangle...
drawing circle...
Runtime Polymorphism with Data
Members
Runtime Polymorphism can be achieved by data members in C++. Let's see an
example where we are accessing the field by reference variable which refers to the
instance of derived class.

1. #include <iostream>  
2. using namespace std;  
3. class Animal {  
4.     public:  
5.     string color = "Black";    
6. };   
7. class Dog: public Animal   
8. {    
9.  public:  
10.     string color = "Grey";    
11. };  
12. int main(void) {  
13.      Animal d= Dog();    
14.     cout<<d.color;   
15. }  

Output:

Black
C++ Overloading (Function and Operator)
If we create two or more members having same name but different in number or
type of parameter, it is known as C++ overloading. In C++, we can overload:

o methods,

o constructors, and

o indexed properties

It is because these members have parameters only.

Types of overloading in C++ are:

o Function overloading

o Operators overloading

C++ Function Overloading


Having two or more function with same name but different in parameters, is known
as function overloading in C++.

The advantage of Function overloading is that it increases the readability of the


program because you don't need to use different names for same action.

C++ Function Overloading Example


Let's see the simple example of function overloading where we are changing
number of arguments of add() method.

1. #include <iostream>  
2. using namespace std;  
3. class Cal {  
4.     public:  
5. static int add(int a,int b){    
6.         return a + b;    
7.     }    
8. static int add(int a, int b, int c)    
9.     {    
10.         return a + b + c;    
11.     }    
12. };   
13. int main(void) {  
14.     Cal C;  
15.     cout<<C.add(10, 20)<<endl;    
16.     cout<<C.add(12, 20, 23);   
17.    return 0;  
18. }  

Output:

30
55

C++ Operators Overloading


Operator overloading is used to overload or redefine most of the operators available
in C++. It is used to perform operation on user define data type.

The advantage of Operators overloading is to perform different operations on the


same operand.

C++ Operators Overloading Example


Let's see the simple example of operator overloading in C++. In this example, void
operator ++ () operator function is defined (inside Test class).

1. #include <iostream>  
2. using namespace std;  
3. class Test  
4. {  
5.    private:  
6.       int num;  
7.    public:  
8.        Test(): num(8){}  
9.        void operator ++()   
10.        {   
11.           num = num+2;   
12.        }  
13.        void Print() {   
14.            cout<<"The Count is: "<<num;   
15.        }  
16. };  
17. int main()  
18. {  
19.     Test tt;  
20.     ++tt;  // calling of a function "void operator ++()"  
21.     tt.Print();  
22.     return 0;  
23. }  

Output:

The Count is: 10


C++ Function Overriding
If derived class defines same function as defined in its base class, it is known as
function overriding in C++. It is used to achieve runtime polymorphism. It enables
you to provide specific implementation of the function which is already provided by
its base class.

C++ Function Overriding Example


1. #include <iostream>  
2. using namespace std;  
3. class Animal {  
4.     public:  
5. void eat(){    
6. cout<<"Eating...";    
7.     }      
8. };   
9. class Dog: public Animal    
10. {    
11.  public:  
12.  void eat()    
13.     {    
14.        cout<<"Eating bread...";    
15.     }    
16. };  
17. int main(void) {  
18.    Dog d = Dog();    
19.    d.eat();  
20.    return 0;  
21. }  

Output:
Eating bread...

C++ virtual function


C++ virtual function is a member function in base class that you redefine in a
derived class. It is declare using the virtual keyword.

It is used to tell the compiler to perform dynamic linkage or late binding on the


function.

Late binding or Dynamic linkage


In late binding function call is resolved during runtime. Therefore compiler
determines the type of object at runtime, and then binds the function call.

C++ virtual function Example


Let's see the simple example of C++ virtual function used to invoked the derived
class in a program.

1. #include <iostream>  
2. using namespace std;  
3. class A  
4. {  
5.  public:  
6.  virtual void display()  
7.  {  
8.   cout << "Base class is invoked"<<endl;  
9.  }  
10. };  
11. class B:public A  
12. {  
13.  public:  
14.  void display()  
15.  {  
16.   cout << "Derived Class is invoked"<<endl;  
17.  }  
18. };  
19. int main()  
20. {  
21.  A* a;    //pointer of base class  
22.  B b;     //object of derived class  
23.  a = &b;  
24.  a->display();   //Late Binding occurs  
25. }  

Output:

Derived Class is invoked


C++
ABSTRACTION
Interfaces in C++ (Abstract Classes)
Abstract classes are the way to achieve abstraction in C++. Abstraction in C++ is the
process to hide the internal details and showing functionality only. Abstraction can be
achieved by two ways:

1. Abstract class

2. Interface

Abstract class and interface both can have abstract methods which are necessary for
abstraction.

C++ Abstract class


In C++ class is made abstract by declaring at least one of its functions as
<>strong>pure virtual function. A pure virtual function is specified by placing "= 0" in
its declaration. Its implementation must be provided by derived classes.

Let's see an example of abstract class in C++ which has one abstract method draw().
Its implementation is provided by derived classes: Rectangle and Circle. Both classes
have different implementation.

1. #include <iostream>  
2. using namespace std;  
3.  class Shape    
4. {    
5.     public:   
6.     virtual void draw()=0;    
7. };    
8.  class Rectangle : Shape    
9. {    
10.     public:  
11.      void draw()    
12.     {    
13.         cout < <"drawing rectangle..." < <endl;    
14.     }    
15. };    
16. class Circle : Shape    
17. {    
18.     public:  
19.      void draw()    
20.     {    
21.         cout <<"drawing circle..." < <endl;    
22.     }    
23. };    
24. int main( ) {  
25.     Rectangle rec;  
26.     Circle cir;  
27.     rec.draw();    
28.     cir.draw();   
29.    return 0;  
30. }  

Output:

drawing rectangle...
drawing circle...
Data Abstraction in C++
In C++ program if we implement class with private and public members then it is an
example of data abstraction.

Let's see the simple example of data abstraction.

1. #include <iostream>  
2. using namespace std;  
3.  class Sum  
4. {  
5. private: int x, y, z;  
6. public:  
7. void add()  
8. {  
9. cout<<"Enter two numbers: ";  
10. cin>>x>>y;  
11. z= x+y;  
12. cout<<"Sum of two number is: "<<z<<endl;  
13. }  
14. };  
15. int main()  
16. {  
17. Sum sm;  
18. sm.add();  
19. return 0;  
20. }  

Output:

Enter two numbers:


3
6
Sum of two number is: 9
C++
Namespaces
C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to handle
the application.

For accessing the class of a namespace, we need to use namespacename::classname. We


can use using keyword so that we don't have to use complete name all the time.

In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.

C++ namespace Example


Let's see the simple example of namespace which include variable and functions.

1. #include <iostream>  
2. using namespace std;  
3. namespace First {    
4.     void sayHello() {   
5.         cout<<"Hello First Namespace"<<endl;          
6.     }    
7. }    
8. namespace Second  {    
9.        void sayHello() {   
10.            cout<<"Hello Second Namespace"<<endl;   
11.        }    
12. }   
13. int main()  
14. {  
15.  First::sayHello();  
16.  Second::sayHello();  
17. return 0;  
18. }  

Output:

Hello First Namespace


Hello Second Namespace
C++ namespace example: by using keyword
Let's see another example of namespace where we are using "using" keyword so that we
don't have to use complete name for accessing a namespace program.

1. #include <iostream>  
2. using namespace std;  
3. namespace First{  
4.    void sayHello(){  
5.       cout << "Hello First Namespace" << endl;  
6.    }  
7. }  
8. namespace Second{  
9.    void sayHello(){  
10.       cout << "Hello Second Namespace" << endl;  
11.    }  
12. }  
13. using namespace First;  
14. int main () {  
15.    sayHello();  
16.    return 0;  
17. }  

Output:

Hello First Namespace


C++
Strings
C++ Strings
In C++, string is an object of std::string class that represents sequence of characters.
We can perform many operations on strings such as concatenation, comparison,
conversion etc.

C++ String Example


Let's see the simple example of C++ string.

1. #include <iostream>  
2. using namespace std;  
3. int main( ) {  
4.     string s1 = "Hello";    
5.         char ch[] = { 'C', '+', '+'};    
6.         string s2 = string(ch);    
7.         cout<<s1<<endl;    
8.         cout<<s2<<endl;    
9. }  

Output:

Hello
C++

C++ String Compare Example


Let's see the simple example of string comparison using strcmp() function.

1. #include <iostream>  
2. #include <cstring>  
3. using namespace std;  
4. int main ()  
5. {  
6.   char key[] = "mango";  
7.   char buffer[50];  
8.   do {  
9.      cout<<"What is my favourite fruit? ";  
10.      cin>>buffer;  
11.   } while (strcmp (key,buffer) != 0);  
12.  cout<<"Answer is correct!!"<<endl;  
13.   return 0;  
14. }  

Output:

What is my favourite fruit? apple


What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!

C++ String Concat Example


Let's see the simple example of string concatenation using strcat() function.

1. #include <iostream>  
2. #include <cstring>  
3. using namespace std;  
4. int main()  
5. {  
6.     char key[25], buffer[25];  
7.     cout << "Enter the key string: ";  
8.     cin.getline(key, 25);  
9.     cout << "Enter the buffer string: ";  
10.      cin.getline(buffer, 25);  
11.     strcat(key, buffer);   
12.     cout << "Key = " << key << endl;  
13.     cout << "Buffer = " << buffer<<endl;  
14.     return 0;  
15. }  
Output:

Enter the key string: Welcome to


Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.

C++ String Copy Example


Let's see the simple example of copy the string using strcpy() function.

1. #include <iostream>  
2. #include <cstring>  
3. using namespace std;  
4. int main()  
5. {  
6.     char key[25], buffer[25];  
7.     cout << "Enter the key string: ";  
8.     cin.getline(key, 25);  
9.     strcpy(buffer, key);  
10.     cout << "Key = "<< key << endl;  
11.     cout << "Buffer = "<< buffer<<endl;  
12.     return 0;  
13. }  

Output:

Enter the key string: C++ Tutorial


Key = C++ Tutorial
Buffer = C++ Tutorial
C++ String Length Example
Let's see the simple example of finding the string length using strlen() function.

1. #include <iostream>  
2. #include <cstring>  
3. using namespace std;  
4. int main()  
5. {  
6.     char ary[] = "Welcome to C++ Programming";  
7.     cout << "Length of String = " << strlen(ary)<<endl;  
8.     return 0;  
9. }  

Output:

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

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

Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed
even after exception.

C++ Exception Classes


In C++ standard exceptions are defined in <exception> class that we can use inside our
programs. The arrangement of parent-child class hierarchy is shown below:
All the exception classes in C++ are derived from std::exception class. Let's see the list of
C++ common exception classes.

Exception Description

std::exception It is an exception and parent class of all standard C++ exceptions.

std::logic_failure It is an exception that can be detected by reading a code.

std::runtime_error It is an exception that cannot be detected by reading a code.

std::bad_exception It is used to handle the unexpected exceptions in a c++ program.

std::bad_cast This exception is generally be thrown by dynamic_cast.

std::bad_typeid This exception is generally be thrown by typeid.

std::bad_alloc This exception is generally be thrown by new.

C++ Exception Handling Keywords


In C++, we use 3 keywords to perform exception handling:

o try

o catch, and

o throw

Moreover, we can create user-defined exception which we will learn in next chapters.
C++ try/catch
In C++ programming, exception handling is performed using try/catch statement. The C+
+ try block is used to place the code that may occur exception. The catch block is used to
handle the exception.

C++ example without try/catch


1. #include <iostream>  
2. using namespace std;  
3. float division(int x, int y) {  
4.    return (x/y);  
5. }  
6. int main () {  
7.    int i = 50;  
8.    int j = 0;  
9.    float k = 0;  
10.       k = division(i, j);  
11.       cout << k << endl;  
12.    return 0;  
13. }  

Output:

Floating point exception (core dumped)


C++ try/catch example
1. #include <iostream>  
2. using namespace std;  
3. float division(int x, int y) {  
4.    if( y == 0 ) {  
5.       throw "Attempted to divide by zero!";  
6.    }  
7.    return (x/y);  
8. }  
9. int main () {  
10.    int i = 25;  
11.    int j = 0;  
12.    float k = 0;  
13.    try {  
14.       k = division(i, j);  
15.       cout << k << endl;  
16.    }catch (const char* e) {  
17.       cerr << e << endl;  
18.    }  
19.    return 0;  
20. }  

Output:

Attempted to divide by zero!


C++ User-Defined Exceptions
The new exception can be defined by overriding and inheriting exception class
functionality.

C++ user-defined exception example


Let's see the simple example of user-defined exception in which std::exception class is
used to define the exception.

1. #include <iostream>  
2. #include <exception>  
3. using namespace std;  
4. class MyException : public exception{  
5.     public:  
6.         const char * what() const throw()  
7.         {  
8.             return "Attempted to divide by zero!\n";  
9.         }  
10. };  
11. int main()  
12. {  
13.     try  
14.     {  
15.         int x, y;  
16.         cout << "Enter the two numbers : \n";  
17.         cin >> x >> y;  
18.         if (y == 0)  
19.         {  
20.             MyException z;  
21.             throw z;  
22.         }  
23.         else  
24.         {  
25.             cout << "x / y = " << x/y << endl;  
26.         }  
27.     }  
28.     catch(exception& e)  
29.     {  
30.         cout << e.what();  
31.     }  
32. }  

Output:

Enter the two numbers :


10
2
x / y = 5

Output:

Enter the two numbers :


10
0
Attempted to divide by zero!
-->

Note: In above example what() is a public method provided by the exception class. It is
used to return the cause of an exception.
C++
Files and Streams
C++ Files and Streams
In C++ programming we are using the iostream standard library, it
provides cin and coutmethods for reading from input and writing to output
respectively.

To read and write from a file we are using the standard C++ library called fstream. Let
us see the data types define in fstream library is:

Data Description
Type

fstream It is used to create files, write information to files, and read


information from files.

ifstream It is used to read information from files.

ofstream It is used to create files and write information to the files.

C++ FileStream example: writing to a file


Let's see the simple example of writing to a text file testout.txt using C++ FileStream
programming.

1. #include <iostream>  
2. #include <fstream>  
3. using namespace std;  
4. int main () {  
5.   ofstream filestream("testout.txt");  
6.   if (filestream.is_open())  
7.   {  
8.     filestream << "Welcome to javaTpoint.\n";  
9.     filestream << "C++ Tutorial.\n";  
10.     filestream.close();  
11.   }  
12.   else cout <<"File opening is fail.";  
13.   return 0;  
14. }  
Output:

The content of a text file testout.txt is set with the data:


Welcome to javaTpoint.
C++ Tutorial.

C++ FileStream example: reading from a file


Let's see the simple example of reading from a text file testout.txt using C++
FileStream programming.

1. #include <iostream>  
2. #include <fstream>  
3. using namespace std;  
4. int main () {  
5.   string srg;  
6.   ifstream filestream("testout.txt");  
7.   if (filestream.is_open())  
8.   {  
9.     while ( getline (filestream,srg) )  
10.     {  
11.       cout << srg <<endl;  
12.     }  
13.     filestream.close();  
14.   }  
15.   else {  
16.       cout << "File opening is fail."<<endl;   
17.     }  
18.   return 0;  
19. }  

Note: Before running the code a text file named as "testout.txt" is need to be created
and the content of a text file is given below:

Welcome to javaTpoint.

C++ Tutorial.

Output:
Welcome to javaTpoint.
C++ Tutorial

C++ Read and Write Example


Let's see the simple example of writing the data to a text file  testout.txt and then
reading the data from the file using C++ FileStream programming.

1. #include <fstream>  
2. #include <iostream>  
3. using namespace std;  
4. int main () {  
5.    char input[75];  
6.    ofstream os;  
7.    os.open("testout.txt");  
8.    cout <<"Writing to a text file:" << endl;  
9.    cout << "Please Enter your name: ";   
10.    cin.getline(input, 100);  
11.    os << input << endl;  
12.    cout << "Please Enter your age: ";   
13.    cin >> input;  
14.    cin.ignore();  
15.    os << input << endl;  
16.    os.close();  
17.    ifstream is;   
18.    string line;  
19.    is.open("testout.txt");   
20.    cout << "Reading from a text file:" << endl;   
21.    while (getline (is,line))  
22.    {  
23.    cout << line << endl;  
24.    }      
25.    is.close();  
26.    return 0;  
27. }  

Output:

Writing to a text file: Please Enter your name: Nakul Jain


Please Enter your age: 22
Reading from a text file: Nakul Jain
22

You might also like