100% found this document useful (1 vote)
576 views148 pages

Oops and C++ Notes

C++ is a general purpose programming language that supports object-oriented, procedural and generic programming. It is a middle-level language that encapsulates both high-level and low-level features. C++ supports object-oriented programming through concepts like inheritance, polymorphism, encapsulation, and abstraction. It has standard libraries for core functionality, common tasks, and data structures. C++ can be used to develop various applications like window applications, client-server applications, device drivers, and embedded firmware. It provides features like classes, references, namespaces, and exception handling that improve on C while maintaining backwards compatibility.

Uploaded by

KARUNA RANA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
576 views148 pages

Oops and C++ Notes

C++ is a general purpose programming language that supports object-oriented, procedural and generic programming. It is a middle-level language that encapsulates both high-level and low-level features. C++ supports object-oriented programming through concepts like inheritance, polymorphism, encapsulation, and abstraction. It has standard libraries for core functionality, common tasks, and data structures. C++ can be used to develop various applications like window applications, client-server applications, device drivers, and embedded firmware. It provides features like classes, references, namespaces, and exception handling that improve on C while maintaining backwards compatibility.

Uploaded by

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

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


possible in C. 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++ provides exception handling using
C. 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 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

C++ 1980 Bjarne Stroustrup


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. }
8. #include<iostream.h> includes the standard input output library functions. It
provides cinand cout methods for reading from input and writing to output respectively.
9. #include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
10. void main() The main() function is the entry point of every program in C++
language. The void keyword specifies that it returns no value.
11. cout << "Welcome to C++ Programming." is used to print the data "Welcome to
C++ Programming." on the console.
12. 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.

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
Function and Description
File

It is used to define the cout, cin and cerr objects, which correspond to standard output stream,
<iostream>
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:

1. int 4;
2. int x y;
3. 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 extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

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

asm dynamic_cast namespace reinterpret_cast bool

explicit new static_cast false catch

operator template friend private class

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

Multiplicative */% Left to right

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

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

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


The single line comment starts with // (double slash). Let's see an example of single line comment
in C++.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x = 11; // x is a variable
6. cout<<x<<"\n";
7. }

Output:

11

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

Output:
35

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

Output:

10
20
30
40
50

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
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 sign) Address operator Determine the address of a variable.

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

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

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 Changes made inside the function is
not 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

We can understand the above program of recursive method call by the figure given below:
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++ Vector
A vector is a sequence container class that implements dynamic array, means size automatically
changes when appending elements. A vector stores the elements in contiguous memory locations
and allocates the memory as needed at run time.

Difference between vector and array


An array follows static approach, means its size cannot be changed during run time while vector
implements dynamic array means it automatically resizes itself when appending elements.

Syntax
Consider a vector 'v1'. Syntax would be:

1. vector<object_type> v1;

Example
Let's see a simple example.

1. #include<iostream>
2. #include<vector>
3. using namespace std;
4. int main()
5. {
6. vector<string> v1;
7. v1.push_back("javaTpoint ");
8. v1.push_back("tutorial");
9. for(vector<string>::iterator itr=v1.begin();itr!=v1.end();++itr)
10. cout<<*itr;
11. return 0;
12. }

Output:

javaTpoint tutorial

In this example, vector class has been used to display the string.

C++ Vector Functions

Function Description
at() It provides a reference to an element.

back() It gives a reference to the last element.

front() It gives a reference to the first element.

swap() It exchanges the elements between two vectors.

push_back() It adds a new element at the end.

pop_back() It removes a last element from the vector.

empty() It determines whether the vector is empty or not.

insert() It inserts new element at the specified position.

erase() It deletes the specified element.

resize() It modifies the size of the vector.

clear() It removes all the elements from the vector.

size() It determines a number of elements in the vector.

capacity() It determines the current capacity of the vector.

assign() It assigns new values to the vector.

operator=() It assigns new values to the vector container.

operator[]() It access a specified element.

end() It refers to the past-lats-element in the vector.


emplace() It inserts a new element just before the position pos.

emplace_back() It inserts a new element at the end.

rend() It points the element preceding the first element of the vector.

rbegin() It points the last element of the vector.

begin() It points the first element of the vector.

max_size() It determines the maximum size that vector can hold.

cend() It refers to the past-last-element in the vector.

cbegin() It refers to the first element of the vector.

crbegin() It refers to the last character of the vector.

crend() It refers to the element preceding the first element of the vector.

data() It writes the data of the vector into an array.

shrink_to_fit() It reduces the capacity and makes it equal to the size of the vector.

C++ Vector at()


It gives a reference to an element.

Syntax
Consider a vector v and k is the position. Syntax would be:

1. vector<object_type> v;
2. v.at(k) ;

Parameter
k: k defines the position of element which is to be returned by at() function.
Return value
It returns the element of specified position.

The following illustration shows how at() function works


If i=0 :

If i=3 :

Example
Let's see a simple example.

1. #include<iostream>
2. #include<vector>
3. using namespace std;
4. int main()
5. {
6. vector<int> v1{1,2,3,4};
7. for(int i=0;i<v1.size();i++)
8. cout<<v1.at(i);
9. return 0;
10. }

Output:

1234

In this example, at() function access the elements of vector .


C++ Deque
Deque stands for double ended queue. It generalizes the queue data structure i.e insertion and
deletion can be performed from both the ends either front or back.

Syntax for creating a deque object:


1. deque<object_type> deque_name;

C++ Deque Functions

Method Description

assign() It assigns new content and replacing the old one.

emplace() It adds a new element at a specified position.

emplace_back() It adds a new element at the end.

emplace_front() It adds a new element in the beginning of a deque.

insert() It adds a new element just before the specified position.

push_back() It adds a new element at the end of the container.

push_front() It adds a new element at the beginning of the container.


pop_back() It deletes the last element from the deque.

pop_front() It deletes the first element from the deque.

swap() It exchanges the contents of two deques.

clear() It removes all the contents of the deque.

empty() It checks whether the container is empty or not.

erase() It removes the elements.

max_size() It determines the maximum size of the deque.

resize() It changes the size of the deque.

shrink_to_fit() It reduces the memory to fit the size of the deque.

size() It returns the number of elements.

at() It access the element at position pos.

operator[]() It access the element at position pos.

operator=() It assigns new contents to the container.

back() It access the last element.

begin() It returns an iterator to the beginning of the deque.

cbegin() It returns a constant iterator to the beginning of the deque.

end() It returns an iterator to the end.


cend() It returns a constant iterator to the end.

rbegin() It returns a reverse iterator to the beginning.

crbegin() It returns a constant reverse iterator to the beginning.

rend() It returns a reverse iterator to the end.

crend() It returns a constant reverse iterator to the end.

front() It access the last element.

C++ List
o List is a contiguous container while vector is a non-contiguous container i.e list stores the
elements on a contiguous memory and vector stores on a non-contiguous memory.
o Insertion and deletion in the middle of the vector is very costly as it takes lot of time in
shifting all the elements. Linklist overcome this problem and it is implemented using list
container.
o List supports a bidirectional and provides an efficient way for insertion and deletion
operations.
o Traversal is slow in list as list elements are accessed sequentially while vector supports a
random access.

Template for list


1. #include<iostream>
2. #include<list>
3. using namespace std;
4. int main()
5. {
6. list<int> l;
7. }

It creates an empty list of integer type values.

List can also be initalised with the parameters.

1. #include<iostream>
2. #include<list>
3. using namespace std;
4. int main()
5. {
6. list<int> l{1,2,3,4};
7. }

List can be initialised in two ways.

1. list<int> new_list{1,2,3,4};
2. or
3. list<int> new_list = {1,2,3,4};

C++ List Functions


Following are the member functions of the list:

Method Description

insert() It inserts the new element before the position pointed by the
iterator.

push_back() It adds a new element at the end of the vector.

push_front() It adds a new element to the front.

pop_back() It deletes the last element.

pop_front() It deletes the first element.

empty() It checks whether the list is empty or not.

size() It finds the number of elements present in the list.

max_size() It finds the maximum size of the list.

front() It returns the first element of the list.


back() It returns the last element of the list.

swap() It swaps two list when the type of both the list are same.

reverse() It reverses the elements of the list.

sort() It sorts the elements of the list in an increasing order.

merge() It merges the two sorted list.

splice() It inserts a new list into the invoking list.

unique() It removes all the duplicate elements from the list.

resize() It changes the size of the list container.

assign() It assigns a new element to the list container.

emplace() It inserts a new element at a specified position.

emplace_back() It inserts a new element at the end of the vector.

emplace_front() It inserts a new element at the beginning of the list.

C++ STL Set


Introduction to set
Sets are part of the C++ STL (Standard Template Library). Sets are the associative containers
that stores sorted key, in which each key is unique and it can be inserted or deleted but cannot be
altered.

Syntax
1. template < class T, // set::key_type/value_type
2. class Compare = less<T>, // set::key_compare/value_compare
3. class Alloc = allocator<T> // set::allocator_type
4. > class set;
Parameter
T: Type of element stored in the container set.

Compare: A comparison class that takes two arguments of the same type bool and returns a
value. This argument is optional and the binary predicate less<T>, is the default value.

Alloc: Type of the allocator object which is used to define the storage allocation model.

Member Functions
Below is the list of all member functions of set:

Constructor/Destructor

Functions Description

(constructor) Construct set

(destructor) Set destructor

operator= Copy elements of the set to another set.

Iterators

Functions Description

Begin Returns an iterator pointing to the first element in the set.

cbegin Returns a const iterator pointing to the first element in the set.

End Returns an iterator pointing to the past-end.

Cend Returns a constant iterator pointing to the past-end.

rbegin Returns a reverse iterator pointing to the end.

Rend Returns a reverse iterator pointing to the beginning.


crbegin Returns a constant reverse iterator pointing to the end.

Crend Returns a constant reverse iterator pointing to the beginning.

Capacity

Functions Description

empty Returns true if set is empty.

Size Returns the number of elements in the set.

max_size Returns the maximum size of the set.

Modifiers

Functions Description

insert Insert element in the set.

Erase Erase elements from the set.

Swap Exchange the content of the set.

Clear Delete all the elements of the set.

emplace Construct and insert the new elements into the set.

emplace_hint Construct and insert new elements into the set by hint.

Observers

Functions Description
key_comp Return a copy of key comparison object.

value_comp Return a copy of value comparison object.

Operations

Functions Description

Find Search for an element with given key.

count Gets the number of elements matching with given key.

lower_bound Returns an iterator to lower bound.

upper_bound Returns an iterator to upper bound.

equal_range Returns the range of elements matches with given key.

Allocator

Functions Description

get_allocator Returns an allocator object that is used to construct the set.

Non-Member Overloaded Functions

Functions Description

operator== Checks whether the two sets are equal or not.

operator!= Checks whether the two sets are equal or not.


operator< Checks whether the first set is less than other or not.

operator<= Checks whether the first set is less than or equal to other or not.

operator> Checks whether the first set is greater than other or not.

operator>= Checks whether the first set is greater than equal to other or not.

swap() Exchanges the element of two sets.

C++ set constructor


There are following five uses of set constructor:

1. default constructor: This is used to construct an empty set container with zero elements.
2. range constructor: This is used to construct a container with the contents of range [first,
last).
3. copy constructor: This is used to construct a set with a copy of the elements of existing
container.
4. move constructor: This is used to construct the container with the elements of other with
the use of move semantics.
5. initializer list constructor: This is used to construct the set with the contents of the
initializer list.

Syntax

Default constructor
1. explicit set (const key_compare& comp = key_compare(),
2. const allocator_type& alloc = allocator_type()); //until C++ 11
3.
4. explicit set (const key_compare& comp = key_compare(),
5. const allocator_type& alloc = allocator_type());
6. explicit set (const allocator_type& alloc); //since C++ 11

range constructor
1. template <class InputIterator>
2. set (InputIterator first, InputIterator last,
3. const key_compare& comp = key_compare(),
4. const allocator_type& alloc = allocator_type()); //until C++ 11
5.
6. template <class InputIterator>
7. set (InputIterator first, InputIterator last,
8. const key_compare& comp = key_compare(),
9. const allocator_type& = allocator_type()); //since C++ 11

copy constructor
1. set (const set& x); //until C++ 11
2.
3. set (const set& x);
4. set (const set& x, const allocator_type& alloc); //since C++ 11

move constructor
1. set (set&& x);
2. set (set&& x, const allocator_type& alloc); //since C++ 11

initializer list constructor


1. set (initializer_list<value_type> il,
2. const key_compare& comp = key_compare(),
3. const allocator_type& alloc = allocator_type()); //since C++ 11

Parameter
comp: A comparison function object which takes two key arguments and returns true if first
argument goes before the second argument otherwise false. By default it uses less<key_type>
predicate.

alloc: A allocator object use for all memory allocations of this container.

first: Input iterator to the first position in a range.

last: Input iterator to the last position in a range.

x: Another set object of the same type.

il: An initializer list object from which the elements are to be copied.

Return value
Constructor never returns any value.

Complexity
For empty constructors and move constructors complexity will be constant.

For all other cases, complexity will be linear in the distance between the iterators if the elements
are already sorted.

Iterator validity
Invalidate all pointers, iterators, and references related to x if the elements of set container are
moved in the move constructor.

Data Races
All copied elements are accessed.

Exception Safety
No effects in case an exception is thrown.

Example 1
Let's see the simple example for default constructor:

1. #include <iostream>
2. #include <set>
3.
4. using namespace std;
5.
6. int main(void) {
7. // Default constructor
8. set<char> s;
9.
10. int size = s.size();
11.
12. cout << "Size of set s = " << size;
13. return 0;
14. }

Output:

Size of set = 0

In the above example, s is an empty set therefore, size is 0.

Example 2
Let's see a simple example for range constructor:

1. #include <iostream>
2. #include <set>
3.
4. using namespace std;
5.
6. int main(void) {
7. int evens[] = {2,4,6,8,10};
8.
9. // Range Constructor
10. set<int> myset (evens, evens+5);
11.
12. cout << "Size of set container myset is : " << myset.size();
13. return 0;
14. }

Output:

Size of set container myset is: 5

In the above example, set myset is constructed with the elements of evens.

Example 3
Let's see a simple example for copy constructor:

1. #include <iostream>
2. #include <set>
3.
4. using namespace std;
5.
6. int main(void) {
7. //Default Constructor
8. std::set<int> s1;
9. s1.insert(5);
10. s1.insert(10);
11.
12. cout << "Size of set container s1 is : " << s1.size();
13.
14. // Copy constructor
15. set<int> s2(s1);
16. cout << "\nSize of new set container s2 is : " << s2.size();
17. return 0;
18. }

Output:

Size of set container s1 is : 2


Size of new set container s2 is : 2

In the above example, s2 is a copy of s1 set.

Example 4
Let's see a simple example for move constructor:
1. #include <iostream>
2. #include <set>
3.
4. using namespace std;
5.
6. int main(void) {
7. // Default constructor
8. set<char> s1;
9. s1.insert('x');
10. s1.insert('y');
11.
12. cout << "Size of set container s1 is : " << s1.size();
13.
14. // Move constructor
15. set<char> s2(move(s1));
16. cout << "\nSize of new set container s2 is : " << s2.size();
17. return 0;
18. }

Output:

Size of set container s1 is : 2


Size of new set container s2 is : 2

In the above example, contents of s1 are moved to s2 set.

Example 5
Let's see a simple example for initializer list constructor:

1. #include <iostream>
2. #include <set>
3. #include <string>
4.
5. using namespace std;
6.
7. int main() {
8. // Initializer list constructor
9. set<string> fruit {
10. "orange", "apple", "mango", "peach", "grape"
11. };
12.
13. cout << "Size of set container fruit is : " << fruit.size();
14. return 0;
15. }
Output:

Size of set container fruit is : 5

The above example creates a set fruit with string as key and initializes it with initializer_list.

C++ ~set destructor


C++ set destructor is used to destroy all the elements of set container and deallocate all the
storage memory allocated by the set container.

Syntax
1. ~set();

Parameter
None

Return value
None

Complexity
Linear in set::size (destructors).

Iterator validity
All iterators, references and pointers are invalidated.

Data Races
The container set and all its elements are modified.

Exception Safety
This function never throws exceptions.

C++ stack
In computer science we go for working on a large variety of programs. Each of them has their own
domain and utility. Based on the purpose and environment of the program creation, we have a
large number of data structures available to choose from. One of them is 'stack'. Before discussing
about this data type let us take a look at its syntax.

Syntax
1. template<class T, class Container = deque<T> > class stack;

This data structure works on the LIFO technique, where LIFO stands for Last In First Out. The
element which was first inserted will be extracted at the end and so on. There is an element called
as 'top' which is the element at the upper most position. All the insertion and deletion operations
are made at the top element itself in the stack.

Stacks in the application areas are implied as the container adaptors.

The containers should have a support for the following list of operations:

o empty
o size
o back
o push_back
o pop_back

Template Parameters
T: The argument specifies the type of the element which the container adaptor will be holding.

Container: The argument specifies an internal object of container where the elements of the stack
are hold.

Member Types
Given below is a list of the stack member types with a short description of the same.

Member Types Description

value_type Element type is specified.

container_type Underlying container type is specified.

size_type It specifies the size range of the elements.

Functions
With the help of functions, an object or variable can be played with in the field of programming.
Stacks provide a large number of functions that can be used or embedded in the programs. A list of
the same is given below:
Function Description

(constructor) The function is used for the construction of a stack container.

empty The function is used to test for the emptiness of a stack. If the
stack is empty the function returns true else false.

size The function returns the size of the stack container, which is a
measure of the number of elements stored in the stack.

top The function is used to access the top element of the stack. The
element plays a very important role as all the insertion and
deletion operations are performed at the top element.

push The function is used for the insertion of a new element at the top
of the stack.

pop The function is used for the deletion of element, the element in
the stack is deleted from the top.

emplace The function is used for insertion of new elements in the stack
above the current top element.

swap The function is used for interchanging the contents of two


containers in reference.

relational The non member function specifies the relational operators that
operators are needed for the stacks.

uses As the name suggests the non member function uses the
allocator<stack> allocator for the stacks.

Example: A simple program to show the use of basic stack functions.


1. #include <iostream>
2. #include <stack>
3. using namespace std;
4. void newstack(stack <int> ss)
5. {
6. stack <int> sg = ss;
7. while (!sg.empty())
8. {
9. cout << '\t' << sg.top();
10. sg.pop();
11. }
12. cout << '\n';
13. }
14. int main ()
15. {
16. stack <int> newst;
17. newst.push(55);
18. newst.push(44);
19. newst.push(33);
20. newst.push(22);
21. newst.push(11);
22.
23. cout << "The stack newst is : ";
24. newstack(newst);
25. cout << "\n newst.size() : " << newst.size();
26. cout << "\n newst.top() : " << newst.top();
27. cout << "\n newst.pop() : ";
28. newst.pop();
29. newstack(newst);
30. return 0;
31. }

Output:

The stack newst is : 11 22 33 44 55

newst.size() : 5
newst.top() : 11
newst.pop() : 22 33 44 55

C++ queue
In computer science we go for working on a large variety of programs. Each of them has their own
domain and utility. Based on the purpose and environment of the program creation, we have a
large number of data structures available to choose from. One of them is 'queues. Before
discussing about this data type let us take a look at its syntax.

Syntax
1. template<class T, class Container = deque<T> > class queue;
This data structure works on the FIFO technique, where FIFO stands for First In First Out. The
element which was first inserted will be extracted at the first and so on. There is an element called
as 'front' which is the element at the front most position or say the first position, also there is an
element called as 'rear' which is the element at the last position. In normal queues insertion of
elements take at the rear end and the deletion is done from the front.

Queues in the application areas are implied as the container adaptors.

The containers should have a support for the following list of operations:

o empty
o size
o push_back
o pop_front
o front
o back

Template Parameters
T: The argument specifies the type of the element which the container adaptor will be holding.

Container: The argument specifies an internal object of container where the elements of the
queues are held.

Member Types
Given below is a list of the queue member types with a short description of the same.

Member Types Description

value_type Element type is specified.

container_type Underlying container type is specified.

size_type It specifies the size range of the elements.

reference It is a reference type of a container.

const_reference It is a reference type of a constant container.

Functions
With the help of functions, an object or variable can be played with in the field of programming.
Queues provide a large number of functions that can be used or embedded in the programs. A list
of the same is given below:

Function Description

(constructor) The function is used for the construction of a queue container.

empty The function is used to test for the emptiness of a queue. If the
queue is empty the function returns true else false.

size The function returns the size of the queue container, which is a
measure of the number of elements stored in the queue.

front The function is used to access the front element of the queue.
The element plays a very important role as all the deletion
operations are performed at the front element.

back The function is used to access the rear element of the queue.
The element plays a very important role as all the insertion
operations are performed at the rear element.

push The function is used for the insertion of a new element at the
rear end of the queue.

pop The function is used for the deletion of element; the element in
the queue is deleted from the front end.

emplace The function is used for insertion of new elements in the queue
above the current rear element.

swap The function is used for interchanging the contents of two


containers in reference.

relational operators The non member function specifies the relational operators that
are needed for the queues.
uses As the name suggests the non member function uses the
allocator<queue> allocator for the queues.

Example: A simple program to show the use of basic queue functions.


1. #include <iostream>
2. #include <queue>
3. using namespace std;
4. void showsg(queue <int> sg)
5. {
6. queue <int> ss = sg;
7. while (!ss.empty())
8. {
9. cout << '\t' << ss.front();
10. ss.pop();
11. }
12. cout << '\n';
13. }
14.
15. int main()
16. {
17. queue <int> fquiz;
18. fquiz.push(10);
19. fquiz.push(20);
20. fquiz.push(30);
21.
22. cout << "The queue fquiz is : ";
23. showsg(fquiz);
24.
25. cout << "\nfquiz.size() : " << fquiz.size();
26. cout << "\nfquiz.front() : " << fquiz.front();
27. cout << "\nfquiz.back() : " << fquiz.back();
28.
29. cout << "\nfquiz.pop() : ";
30. fquiz.pop();
31. showsg(fquiz);
32.
33. return 0;
34. }

Output:

The queue fquiz is : 10 20 30

fquiz.size() : 3
fquiz.front() : 10
fquiz.back() : 30
fquiz.pop() : 20 30

C++ map function


Maps are part of the C++ STL (Standard Template Library). Maps are the associative containers
that store sorted key-value pair, in which each key is unique and it can be inserted or deleted but
cannot be altered. Values associated with keys can be changed.

For example: A map of Employees where employee ID is the key and name is the value can be
represented as:

Keys Values

101 Nikita

102 Robin

103 Deep

104 John

Syntax
1. template < class Key, // map::key_type
2. class T, // map::mapped_type
3. class Compare = less<Key>, // map::key_compare
4. class Alloc = allocator<pair<const Key,T> > // map::allocator_type
5. > class map;

Parameter
key: The key data type to be stored in the map.

type: The data type of value to be stored in the map.

compare: A comparison class that takes two arguments of the same type bool and returns a
value. This argument is optional and the binary predicate less<"key"> is the default value.

alloc: Type of the allocator object. This argument is optional and the default value is allocator .

Creating a map
Maps can easily be created using the following statement:

1. typedef pair<const Key, T> value_type;

The above form will use to create a map with key of type Key type and value of type value
type.One important thing is that key of a map and corresponding values are always inserted as a
pair, you cannot insert only key or just a value in a map.

Example 1
1. #include <string.h>
2. #include <iostream>
3. #include <map>
4. #include <utility>
5. using namespace std;
6. int main()
7. {
8. map<int, string> Employees;
9. // 1) Assignment using array index notation
10. Employees[101] = "Nikita";
11. Employees[105] = "John";
12. Employees[103] = "Dolly";
13. Employees[104] = "Deep";
14. Employees[102] = "Aman";
15. cout << "Employees[104]=" << Employees[104] << endl << endl;
16. cout << "Map size: " << Employees.size() << endl;
17. cout << endl << "Natural Order:" << endl;
18. for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii)
19. {
20. cout << (*ii).first << ": " << (*ii).second << endl;
21. }
22. cout << endl << "Reverse Order:" << endl;
23. for( map<int,string>::reverse_iterator ii=Employees.rbegin(); ii!=Employees.rend(); ++ii)
24. {
25. cout << (*ii).first << ": " << (*ii).second << endl;
26. }
27. }

Output:

Employees[104]=Deep

Map size: 5

Natural Order:
101: Nikita
102: Aman
103: Dolly
104: Deep
105: John

Reverse Order:
105: John
104: Deep
103: Dolly
102: Aman
101: Nikita

Member Functions
Below is the list of all member functions of map:

Constructor/Destructor
Functions Description

constructors Construct map

destructors Map destructor

operator= Copy elements of the map to another map.

Iterators
Functions Description

begin Returns an iterator pointing to the first element in the map.

cbegin Returns a const iterator pointing to the first element in the map.

end Returns an iterator pointing to the past-end.

cend Returns a constant iterator pointing to the past-end.

rbegin Returns a reverse iterator pointing to the end.

rend Returns a reverse iterator pointing to the beginning.


crbegin Returns a constant reverse iterator pointing to the end.

crend Returns a constant reverse iterator pointing to the beginning.

Capacity
Functions Description

empty Returns true if map is empty.

size Returns the number of elements in the map.

max_size Returns the maximum size of the map.

Element Access
Functions Description

operator[] Retrieve the element with given key.

at Retrieve the element with given key.

Modifiers
Functions Description

insert Insert element in the map.

erase Erase elements from the map.

swap Exchange the content of the map.

clear Delete all the elements of the map.


emplace Construct and insert the new elements into the map.

emplace_hint Construct and insert new elements into the map by hint.

Observers
Functions Description

key_comp Return a copy of key comparison object.

value_comp Return a copy of value comparison object.

Operations
Functions Description

find Search for an element with given key.

count Gets the number of elements matching with given key.

lower_bound Returns an iterator to lower bound.

upper_bound Returns an iterator to upper bound.

equal_range Returns the range of elements matches with given key.

Allocator
Functions Description

get_allocator Returns an allocator object that is used to construct the map.

Non-Member Overloaded Functions


Functions Description
operator== Checks whether the two maps are equal or not.

operator!= Checks whether the two maps are equal or not.

operator< Checks whether the first map is less than other or not.

operator<= Checks whether the first map is less than or equal to other or not.

operator> Checks whether the first map is greater than other or not.

operator>= Checks whether the first map is greater than equal to other or not.

swap() Exchanges the element of two maps.

C++ multimap
Multimaps are part of the C++ STL (Standard Template Library). Multimaps are the
associative containers like map that stores sorted key-value pair, but unlike maps which store only
unique keys, multimap can have duplicate keys. By default it uses < operator to compare the
keys.

For example: A multimap of Employees where employee age is the key and name is the value can
be represented as:

Keys Values

23 Nikita

28 Robin

25 Deep

25 Aman

Multimap employee has duplicate keys age.


Syntax
1. template < class Key, // multimap::key_type
2. class T, // multimap::mapped_type
3. class Compare = less<Key>, // multimap::key_compare
4. class Alloc = allocator<pair<const Key,T> > // multimap::allocator_type
5. > class multimap;

Parameter
key: The key data type to be stored in the multimap.

type: The data type of value to be stored in the multimap.

compare: A comparison class that takes two arguments of the same type bool and returns a
value. This argument is optional and the binary predicate less<"key"> is the default value.

alloc: Type of the allocator object. This argument is optional and the default value is allocator .

Creating a multimap
Multimaps can easily be created using the following statement:

1. typedef pair<const Key, T> value_type;

The above form will use to create a multimap with key of type Key_type and value of
type value_type. One important thing is that key of a multimap and corresponding values are
always inserted as a pair, you cannot insert only key or just a value in a multimap.

Example
1. #include <iostream>
2. #include <map>
3. #include <string>
4.
5. using namespace std;
6.
7. int main()
8. {
9. multimap<string, string> m = {
10. {"India","New Delhi"},
11. {"India", "Hyderabad"},
12. {"United Kingdom", "London"},
13. {"United States", "Washington D.C"}
14. };
15.
16. cout << "Size of map m: " << m.size() <<endl;
17. cout << "Elements in m: " << endl;
18.
19. for (multimap<string, string>::iterator it = m.begin(); it != m.end(); ++it)
20. {
21. cout << " [" << (*it).first << ", " << (*it).second << "]" << endl;
22. }
23.
24. return 0;
25. }

Output:

Size of map m: 4
Elements in m:
[India, New Delhi]
[India, Hyderabad]
[United Kingdom, London]
[United States, Washington D.C]

Member Functions
Below is the list of all member functions of multimap:

Constructor/Destructor
Functions Description

constructor Construct multimap

destructor Multimap destructor

operator= Copy elements of the multimap to another multimap.

Iterators
Functions Description

begin Returns an iterator pointing to the first element in the multimap.

cbegin Returns a const_iterator pointing to the first element in the multimap.


end Returns an iterator pointing to the past-end.

cend Returns a constant iterator pointing to the past-end.

rbegin Returns a reverse iterator pointing to the end.

rend Returns a reverse iterator pointing to the beginning.

crbegin Returns a constant reverse iterator pointing to the end.

crend Returns a constant reverse iterator pointing to the beginning.

Capacity
Functions Description

empty Return true if multimap is empty.

size Returns the number of elements in the multimap.

max_size Returns the maximum size of the multimap.

Modifiers
Functions Description

insert Insert element in the multimap.

erase Erase elements from the multimap.

swap Exchange the content of the multimap.

clear Delete all the elements of the multimap.


emplace Construct and insert the new elements into the multimap.

emplace_hint Construct and insert new elements into the multimap by hint.

Observers
Functions Description

key_comp Return a copy of key comparison object.

value_comp Return a copy of value comparison object.

Operations
Functions Description

find Search for an element with given key.

count Gets the number of elements matching with given key.

lower_bound Returns an iterator to lower bound.

upper_bound Returns an iterator to upper bound.

equal_range() Returns the range of elements matches with given key.

Allocator
Functions Description

get_allocator Returns an allocator object that is used to construct the multimap.

Non-Member Overloaded Functions


Functions Description

operator== Checks whether the two multimaps are equal or not.

operator!= Checks whether the two multimaps are equal or not.

operator< Checks whether the first multimap is less than other or not.

operator<= Checks whether the first multimap is less than or equal to other or not.

operator> Checks whether the first multimap is greater than other or not.

operator>= Checks whether the first multimap is greater than equal to other or not.

swap() Exchanges the element of two multimaps.

C++ map function


Maps are part of the C++ STL (Standard Template Library). Maps are the associative containers
that store sorted key-value pair, in which each key is unique and it can be inserted or deleted but
cannot be altered. Values associated with keys can be changed.

For example: A map of Employees where employee ID is the key and name is the value can be
represented as:

Keys Values

101 Nikita

102 Robin

103 Deep

104 John
Syntax
1. template < class Key, // map::key_type
2. class T, // map::mapped_type
3. class Compare = less<Key>, // map::key_compare
4. class Alloc = allocator<pair<const Key,T> > // map::allocator_type
5. > class map;

Parameter
key: The key data type to be stored in the map.

type: The data type of value to be stored in the map.

compare: A comparison class that takes two arguments of the same type bool and returns a
value. This argument is optional and the binary predicate less<"key"> is the default value.

alloc: Type of the allocator object. This argument is optional and the default value is allocator .

Creating a map
Maps can easily be created using the following statement:

1. typedef pair<const Key, T> value_type;

The above form will use to create a map with key of type Key type and value of type value
type.One important thing is that key of a map and corresponding values are always inserted as a
pair, you cannot insert only key or just a value in a map.

Example 1
1. #include <string.h>
2. #include <iostream>
3. #include <map>
4. #include <utility>
5. using namespace std;
6. int main()
7. {
8. map<int, string> Employees;
9. // 1) Assignment using array index notation
10. Employees[101] = "Nikita";
11. Employees[105] = "John";
12. Employees[103] = "Dolly";
13. Employees[104] = "Deep";
14. Employees[102] = "Aman";
15. cout << "Employees[104]=" << Employees[104] << endl << endl;
16. cout << "Map size: " << Employees.size() << endl;
17. cout << endl << "Natural Order:" << endl;
18. for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii)
19. {
20. cout << (*ii).first << ": " << (*ii).second << endl;
21. }
22. cout << endl << "Reverse Order:" << endl;
23. for( map<int,string>::reverse_iterator ii=Employees.rbegin(); ii!=Employees.rend(); ++ii)
24. {
25. cout << (*ii).first << ": " << (*ii).second << endl;
26. }
27. }

Output:

Employees[104]=Deep

Map size: 5

Natural Order:
101: Nikita
102: Aman
103: Dolly
104: Deep
105: John

Reverse Order:
105: John
104: Deep
103: Dolly
102: Aman
101: Nikita

Member Functions
Below is the list of all member functions of map:

Constructor/Destructor
Functions Description

constructors Construct map

destructors Map destructor

operator= Copy elements of the map to another map.


Iterators
Functions Description

begin Returns an iterator pointing to the first element in the map.

cbegin Returns a const iterator pointing to the first element in the map.

end Returns an iterator pointing to the past-end.

cend Returns a constant iterator pointing to the past-end.

rbegin Returns a reverse iterator pointing to the end.

rend Returns a reverse iterator pointing to the beginning.

crbegin Returns a constant reverse iterator pointing to the end.

crend Returns a constant reverse iterator pointing to the beginning.

Capacity
Functions Description

empty Returns true if map is empty.

size Returns the number of elements in the map.

max_size Returns the maximum size of the map.

Element Access
Functions Description

operator[] Retrieve the element with given key.


at Retrieve the element with given key.

Modifiers
Functions Description

insert Insert element in the map.

erase Erase elements from the map.

swap Exchange the content of the map.

clear Delete all the elements of the map.

emplace Construct and insert the new elements into the map.

emplace_hint Construct and insert new elements into the map by hint.

Observers
Functions Description

key_comp Return a copy of key comparison object.

value_comp Return a copy of value comparison object.

Operations
Functions Description

find Search for an element with given key.

count Gets the number of elements matching with given key.


lower_bound Returns an iterator to lower bound.

upper_bound Returns an iterator to upper bound.

equal_range Returns the range of elements matches with given key.

Allocator
Functions Description

get_allocator Returns an allocator object that is used to construct the map.

Non-Member Overloaded Functions


Functions Description

operator== Checks whether the two maps are equal or not.

operator!= Checks whether the two maps are equal or not.

operator< Checks whether the first map is less than other or not.

operator<= Checks whether the first map is less than or equal to other or not.

operator> Checks whether the first map is greater than other or not.

operator>= Checks whether the first map is greater than equal to other or not.

swap() Exchanges the element of two maps.

C++ bitset Functions


The various C++ bitset functions are as follows:
Function

all()

any()

count()

flip()

none()

operator[]

reset()

set()

size()

test()

to_string()

to_ullong()

to_ulong()()

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:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 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++.

 Default constructor
 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


Let's see an example of constructor and destructor in C++ which is called automatically.

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

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

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


 It can be used to refer current class instance variable.
 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.

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. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }

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++ static field example: Counting Objects


Let's see another example of static keyword in C++ which counts the objects.

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

201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3

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


 enum improves type safety
 enum can be easily used in switch
 enum can be traversed
 enum can have fields, constructors and methods
 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++ 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++ 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.

Let's see the example of multi level inheritance in C++.

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

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

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

 Compile time polymorphism: It is achieved by function overloading and operator overloading which is
also known as static binding or early binding.
 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:

 methods,
 constructors, and
 indexed properties

It is because these members have parameters only.

Types of overloading in C++ are:

 Function overloading
 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


Let's see a simple example of Function overriding in C++. In this example, we are overriding the eat()
function.

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

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

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

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++ String Functions


Function Description

int compare(const string& str) It is used to compare two string objects.

int length() It is used to find the length of the string.

void swap(string& str) It is used to swap the values of two string objects.

string substr(int pos,int n) It creates a new string object of n characters.

int size() It returns the length of the string in terms of bytes.

void resize(int n) It is used to resize the length of the string up to n characters.


string& replace(int pos,int It replaces portion of the string that begins at character position pos and
len,string& str) spans len characters.

string& append(const string& str) It adds new characters at the end of another string object.

char& at(int pos) It is used to access an individual character at specified position pos.

int find(string& str,int pos,int n) It is used to find the string specified in the parameter.

int find_first_of(string& str,int


It is used to find the first occurrence of the specified sequence.
pos,int n)

int find_first_not_of(string& str,int It is used to search the string for the first character that does not match
pos,int n ) with any of the characters specified in the string.

int find_last_of(string& str,int


It is used to search the string for the last character of specified sequence.
pos,int n)

int find_last_not_of(string& str,int It searches for the last character that does not match with the specified
pos) sequence.

It inserts a new character before the character indicated by the position


string& insert()
pos.

int max_size() It finds the maximum length of the string.

void push_back(char ch) It adds a new character ch at the end of the string.

void pop_back() It removes a last character of the string.

string& assign() It assigns new value to the string.

int copy(string& str) It copies the contents of string into another.

char& back() It returns the reference of last character.

Iterator begin() It returns the reference of first character.

int capacity() It returns the allocated space for the string.

const_iterator cbegin() It points to the first element of the string.

const_iterator cend() It points to the last element of the string.

void clear() It removes all the elements from the string.

const_reverse_iterator crbegin() It points to the last character of the string.


const_char* data() It copies the characters of string into an array.

bool empty() It checks whether the string is empty or not.

string& erase() It removes the characters as specified.

char& front() It returns a reference of the first character.

string& operator+=() It appends a new character at the end of the string.

string& operator=() It assigns a new value to the string.

char operator[](pos) It retrieves a character at specified position pos.

int rfind() It searches for the last occurrence of the string.

iterator end() It references the last character of the string.

reverse_iterator rend() It points to the first character of the string.

void shrink_to_fit() It reduces the capacity and makes it equal to the size of the string.

It returns pointer to an array that contains null terminated sequence of


char* c_str()
characters.

const_reverse_iterator crend() It references the first character of the string.

reverse_iterator rbegin() It reference the last character of the string.

void reserve(inr len) It requests a change in capacity.

allocator_type get_allocator(); It returns the allocated object associated with the string.

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:

 try
 catch, and
 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

In C++ programming we are using the iostream standard library, it provides cin and cout methods 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 Type Description

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
Unit – V
Friend function-

In C++ a function or an entire class may be declared to be a friend of another class or function. A
friend function can also be used for function overloading.

Friend function declaration can appear anywhere in the class. But a good practice would be where
the class ends. An ordinary function that is not the member function of a class has no privilege to
access the private data members, but the friend function does have the capability to access any
private data members. The declaration of the friend function is very simple. The keyword friend in
the class prototype inside the class definition precedes it.

Example to Demonstrate working of friend Function


/* C++ program to demonstrate the working of friend function.*/#include <iostream>

using namespace std;

class Distance {

private:

int meter;

public:

Distance(): meter(0){ }

friend int func(Distance); //friend function

};

int func(Distance d){

//function definition

d.meter=10; //accessing private data from non-member function

return d.meter;

}
int main(){ Distance D;

cout<<"Distace: "<<func(D);

system("pause");

return 0;

Program Output:

Here, friend function func() is declared inside Distance class. So, the private data can be accessed
from this function. Though this example gives you what idea about the concept of friend function.

In C++, friend means to give permission to a class or function. The non-member function has to
grant an access to update or access the class.

The advantage of encapsulation and data hiding is that a non-member function of the class cannot
access a member data of that class. Care must be taken using friend function because it breaks
the natural encapsulation, which is one of the advantages of object-oriented programming. It is
best used in the operator overloading.

Virtual function-

Polymorphism refers to the property by which objects belonging to different classes are able to
respond to the same message but in different forms. When there are C++ functions with the same
name in both superclass as well as a subclass, virtual functions gives programmer capability to call
a member function of a different class by the same function call based upon different context. This
feature is known as polymorphism which is one of the important features of OOP. The pointer is
also one of the key aspects of C++ language similar to that of C. In this chapter, we will be dealing
with virtual functions and pointers of C++.
What is virtual function?

A virtual function is a special form of member function that is declared within a base class and
redefined by a derived class. The keyword virtual is used to create a virtual function, precede the
function's declaration in the base class. If a class includes a virtual function and if it gets inherited,
the virtual class redefines a virtual function to go with its own need. In other words, a virtual
function is a function which gets override in the derived class and instructs the C++ compiler for
executing late binding on that function. A function call is resolved at runtime in late binding and so
compiler determines the type of object at runtime.

Program for Virtual Function:


Example:

#include

using namespace std;

class b

public:

virtual void show()

cout<<"\n Showing base class....";

void display()

cout<<"\n Displaying base class...." ;

};

class d:public b
{

public:

void display()

cout<<"\n Displaying derived class....";

void show()

cout<<"\n Showing derived class....";

};

int main()

b B;

b *ptr;

cout<<"\n\t P points to base:\n" ; ptr=&B; ptr->display();

ptr->show();

cout<<"\n\n\t P points to drive:\n"; d D; ptr=&D; ptr->display();

ptr->show();

Program Output:

P points to base:

Displaying base class....

Showing base class....


P points to drive:

Displaying base class....

Showing derived class....

Dynamic memory management -


Often some situation arises in programming where data or input is dynamic in nature, i.e. the
number of data item keeps changing during program execution. A live scenario where the program
is developed to process lists of employees of an organization. The list grows as the names are
added and shrink as the names get deleted. With the increase in name the memory allocate space
to the list to accommodate additional data items. Such situations in programming require dynamic
memory management techniques.

What is memory Allocation?


There are two ways via which memories can be allocated for storing data. The two ways are:

1. Compile time allocation or static allocation of memory: where the memory for named variables is
allocated by the compiler. Exact size and storage must be known at compile time and for array
declaration, the size has to be constant.
2. Runtime allocation or dynamic allocation of memory: where the memory is allocated at runtime
and the allocation of memory space is done dynamically within the program run and the memory
segment is known as a heap or the free store. In this case, the exact space or number of the item
does not have to be known by the compiler in advance. Pointers play a major role in this case.

What is Dynamic memory allocation?


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

 Creating the dynamic space in memory


 Storing its address in a pointer (so that space can be accessed)

Memory de-allocation is also a part of this concept where the "clean-up" of space is done for
variables or other data storage. It is the job of the programmer to de-allocate dynamically created
space. For de-allocating dynamic memory, we use the delete operator. In other words, dynamic
memory Allocation refers to performing memory management for dynamic memory allocation
manually.

Memory in your C++ program is divided into two parts:

 stack: All variables declared inside any function takes up memory from the stack.
 heap: It is the unused memory of the program and can be used to dynamically allocate the
memory at runtime.

Allocating space for new –To allocate space dynamically, use the unary operator new,
followed by the type being allocated.

Here is a code snippet showing the use of new:

new int; //dynamically allocates an integer type

new double; // dynamically allocates an double type

new int[60];

The above-declared statements are not so useful as the allocated space has no names. But the
lines written below are useful:

int * p; // declares a pointer p

p = new int; // dynamically allocate an int for loading the address in p

double * d; // declares a pointer d

d = new double; // dynamically allocate a double and loading the address in p

The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc()
function. malloc() allocates requested size of bytes and returns a pointer to the first byte of
allocated space. The main benefit of new over malloc() is that new doesn't just allocate memory, it
constructs objects which is a prime concept of C++. When programmers think that the dynamically
allocated variable is not required anymore, they can use the delete operator to free up memory
space. The syntax of using this is:

delete var_name;

Here is a simple program showing the concept of dynamic memory allocation:


Example:

#include <iostream>

using namespace std;

int main()

double* val = NULL;

val = new double;

*val = 38184.26;

cout << "Value is : " << *val << endl;

delete val;

Dynamic Memory Allocation for Arrays


If you as a programmer; wants to allocate memory for an array of characters, i.e., a string of 40
characters. Using that same syntax, programmers can allocate memory dynamically as shown
below.

char* val = NULL; // Pointer initialized with NULL value

val = new char[40]; // Request memory for the variable

Another Dynamic Allocation Program Using Constructor


Example:

#include <iostream>

using namespace std;

class stud {

public:
stud()

cout << "Constructor Used" << endl;

~stud()

cout << "Destructor Used" << endl;

};

int main()

stud* S = new stud[6];

delete[] S;

Difference between static and dynamic memory allocation –Memory allocation


in programming is very important for storing values when you assign them to variables. The
allocation is done either before or at the time of program execution. This eventually allocates
memory for the variables declared by a programmer via the compiler.The major difference between
static and dynamic memory allocations are:

Static Memory Allocation Dynamic Memory Allocation

In this case, variables get allocated permanently In this case, variables get allocated only if your program
unit gets active

Allocation is done before program execution Allocation is done during program execution

It uses the data structure called stack for It uses the data structure called heap for implementing
implementing static allocation dynamic allocation
Less efficient More efficient

There is no memory reusability There is memory reusability and memory can be freed
when not required

Namespaces –

Let's take a situation where there are two students with the same name in an institution. Then we
have to differentiate them in a different manner and more likely we have to add some more
information along with their name, like roll number or parents name or email address. The same
situation may arise in C++ programming also where you might write some code having function
name i.e. fun() and there is already existing another library having same function name. This
makes the compiler halt down and left it with no way to know which of these two function to use
within the C++ program. Namespaces are used to solve this situation.

String- In C++, the one-dimensional array of characters are called strings, which is terminated
by a null character \0.

String declaration in C++ - There are two ways to declare a string in C++:
Example:
Through an array of characters:

char greeting[6];

Through pointers:

char *greeting;

String initialization in C++ -

Example:

char greeting[6] = {'C', 'l', 'o', 'u', 'd', '

char greeting[6] = {'C', 'l', 'o', 'u', 'd', '\0'};

'};

or
char greeting[] = "Cloud";

Memory Representation of above-Defined string in C++

Example:

#include <iostream>

using namespace std;

int main ()

char greeting[6] = {'C', 'l', 'o', 'u', 'd', '

#include <iostream>

using namespace std;

int main ()

char greeting[6] = {'C', 'l', 'o', 'u', 'd', '\0'};

cout << "Tutorials" << greeting << endl;

system("pause");

return 0;

'};

cout << "Tutorials" << greeting << endl;


system("pause");
return 0;
}
Program Output:

C++ Manipulating Strings-

A string is a sequence of character. As you know that C++ does not support built-in string type, you
have used earlier those null character based terminated array of characters to store and
manipulate strings. These strings are termed as C Strings. It often becomes inefficient performing
operations on C strings. Programmers can also define their own string classes with appropriate
member functions to manipulate strings. ANSI standard C++ introduces a new class
called string which is an improvised version of C strings in several ways. In many cases, the strings
object may be treated like any other built-in data type. The string is treated as another container
class for C++.

The C style string-

The C style string belongs to C language and continues to support in C++ also strings in C are the
one-dimensional array of characters which gets terminated by \0 (null character).

This is how the strings in C are declared:

char ch[6] = {'H', 'e', 'l', 'l', 'o', '

char ch[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

'};

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the \0 at the end of the string when it initializes the array.
String Class in C++
The string class is huge and includes many constructors, member functions, and operators.

Programmers may use the constructors, operators and member functions to achieve the following:

 Creating string objects


 Reading string objects from keyboard
 Displaying string objects to the screen
 Finding a substring from a string
 Modifying string
 Adding objects of string
 Comparing strings
 Accessing characters of a string
 Obtaining the size or length of a string, etc...

Manipulate terminated strings null-

C++ supports a wide range of functions that manipulate null-terminated strings. These are:

 strcpy(str1, str2): Copies string str2 into string str1.


 strcat(str1, str2): Concatenates string str2 onto the end of string str1.
 strlen(str1): Returns the length of string str1.
 strcmp(str1, str2): Returns 0 if str1 and str2 are the same; less than 0 if str1<str2; greater than 0 if
str1>str2.
 strchr(str1, ch): Returns a pointer to the first occurrence of character ch in string str1.
 strstr(str1, str2): Returns a pointer to the first occurrence of string str2 in string str1.

Important functions supported by String Class


 append(): This function appends a part of a string to another string
 assign():This function assigns a partial string
 at(): This function obtains the character stored at a specified location
 begin(): This function returns a reference to the start of the string
 capacity(): This function gives the total element that can be stored
 compare(): This function compares a string against the invoking string
 empty(): This function returns true if the string is empty
 end(): This function returns a reference to the end of the string
 erase(): This function removes character as specified
 find(): This function searches for the occurrence of a specified substring
 length(): It gives the size of a string or the number of elements of a string
 swap(): This function swaps the given string with the invoking one

Important Constructors obtained by String Class


 String(): This constructor is used for creating an empty string
 String(const char *str): This constructor is used for creating string objects from a null-terminated
string
 String(const string *str): This constructor is used for creating a string object from another string
object

Operators used for String Objects


1. =: assignment
2. +: concatenation
3. ==: Equality
4. !=: Inequality
5. <: Less than
6. <=: Less than or equal
7. >: Greater than
8. >=: Greater than or equal
9. []: Subscription
10. <<: Output
11. >>: Input

Exceptional handling-
It's very rare that a large program or software works correctly the first time. It might have errors.

The two most common types of errors are:

 Logical errors
 Syntactic errors

Programmers can debug these errors by exhausting debugging and testing procedures. But
programmers often come across some peculiar problems in addition logic or syntax errors. These
types of errors are known as exceptions. Exceptions are run-time anomalies or unusual logical
conditions that may come up while executing the C ++ program. In this chapter, you will learn
about these anomalies and how to handle these anomalies within a C++ program.

What is exception handling?


Exceptions allow a method to react to exceptional circumstances and errors (like runtime errors)
within programs by transferring control to special functions called handlers. For catching
exceptions, a portion of code is placed under exception inspection. Exception handling was not a
part of the original C++. It is a new feature that ANSI C++ included in it. Now almost all C++
compilers support this feature. Exception handling technology offers a securely integrated
approach to avoid the unusual predictable problems that arise while executing a program.

There are two types of exceptions:

1. Synchronous exceptions
2. Asynchronous exceptions

Errors such as: out of range index and overflow fall under the category of synchronous type
exceptions. Those errors that are caused by events beyond the control of the program are
called asynchronous exceptions. The main motive of the exceptional handling concept is to
provide a means to detect and report an exception so that appropriate action can be taken. This
mechanism needs a separate error handling code that performs the following tasks:

 Find and hit the problem (exception)


 Inform that the error has occurred (throw exception)
 Receive the error information (Catch the exception)
 Take corrective actions (handle exception)

The error handling mechanism basically consists of two parts. These are:

1. To detect errors
2. To throw exceptions and then take appropriate actions

Exception handling in C++ is built on three keywords: try, catch, and throw.

 try
 throw: A program throws an exception when a problem is detected which is done using a
keyword "throw".
 catch: A program catches an exception with an exception handler where programmers want to
handle the anomaly. The keyword catch is used for catching exceptions.
The Catch blocks catching exceptions must immediately follow the try block that throws an
exception.

The general form of these two blocks is as follows:

Syntax:

try

throw exception;

catch(type arg)

//some code

If the try block throws an exception then program control leaves the block and enters into the catch
statement of the catch block. If the type of object thrown matches the argument type in the catch
statement, the catch block is executed for handling the exception. Divided-by-zero is a common
form of exception generally occurred in arithmetic based programs.

A Simple Program of Exception Handling in C++


Example:

#include<iostream>

using namespace std;

int main()

try {

throw 6;
}

catch (int a) {

cout << "An exception occurred!" << endl;

cout << "Exception number is: " << a << endl;

The following example shows handling of division by zero exception.

Example:

#include<iostream>

using namespace std;

double division(int var1, int var2)

if (var2 == 0) {

throw "Division by Zero.";

return (var1 / var2);

int main()

int a = 30;

int b = 0;

double d = 0;
try {

d = division(a, b);

cout << d << endl;

catch (const char* error) {

cout << error << endl;

return 0;

Example:

Division by zero.

Advantages of Exception Handling


1. Programmers can deal with them at some level within the program
2. If an error can't be dealt with at one level, then it will automatically be shown at the next level,
where it can be dealt with.

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.

You might also like