Oops and C++ Notes
Oops and C++ Notes
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.
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++
2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
outside users.
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.
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.
Let's see the programming languages that were developed before C++ language.
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.
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.
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.
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.
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.
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:
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:
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++ 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.
1. type variable_list;
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:
A variable name can start with alphabet and underscore only. It can't start with digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
1. int a;
2. int _ab;
3. int a30;
1. int 4;
2. int x y;
3. int double;
A data type specifies the type of data that a variable can store such as integer, floating, character etc.
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.
float 4 byte
double 8 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.
A list of 30 Keywords in C++ Language which are not available in C language are given
below.
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
int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before +
(additive operator).
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
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
Output:
Enter a number:11
It is odd number
Output:
Enter a number:12
It is even number
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. }
Output:
Output:
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. }
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.
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.
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
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. for (; ;)
6. {
7. cout<<"Infinitive For Loop";
8. }
9. }
Output:
1. while(condition){
2. //code to be executed
3. }
Flowchart:
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
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
1. #include <iostream>
2. using namespace std;
3. int main () {
4. while(true)
5. {
6. cout<<"Infinitive While Loop";
7. }
8. }
Output:
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
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
1. do{
2. //code to be executed
3. }while(true);
Output:
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c
1. jump-statement;
2. break;
Flowchart:
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
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
1. jump-statement;
2. continue;
Output:
1
2
3
4
6
7
8
9
10
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
It can be used to transfer control from deeply nested loop or switch case label.
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:
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
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.
Output:/p>
10
0
20
0
30
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
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:
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:
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:
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
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.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.
Pointers in c language are widely used in arrays, functions and structures. It reduces the code and
improves the performance.
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
Output
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
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:
Declaration of a function
The syntax of creating function in C++ language is given below:
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
Let's understand call by value and call by reference in C++ language one by one.
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:
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:
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.
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:
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
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.
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
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.
Function Description
at() It provides a reference to an element.
rend() It points the element preceding the first element of the vector.
crend() It refers to the element preceding the first element of the vector.
shrink_to_fit() It reduces the capacity and makes it equal to the size of the vector.
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.
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
Method Description
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.
1. #include<iostream>
2. #include<list>
3. using namespace std;
4. int main()
5. {
6. list<int> l{1,2,3,4};
7. }
1. list<int> new_list{1,2,3,4};
2. or
3. list<int> new_list = {1,2,3,4};
Method Description
insert() It inserts the new element before the position pointed by the
iterator.
swap() It swaps two list when the type of both the list are same.
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
Iterators
Functions Description
cbegin Returns a const iterator pointing to the first element in the set.
Capacity
Functions Description
Modifiers
Functions Description
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.
Operations
Functions Description
Allocator
Functions Description
Functions Description
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.
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
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.
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
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:
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:
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:
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:
The above example creates a set fruit with string as key and initializes it with initializer_list.
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.
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.
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
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.
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.
Output:
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.
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.
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
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.
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.
Output:
fquiz.size() : 3
fquiz.front() : 10
fquiz.back() : 30
fquiz.pop() : 20 30
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.
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:
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
Iterators
Functions Description
cbegin Returns a const iterator pointing to the first element in the map.
Capacity
Functions Description
Element Access
Functions Description
Modifiers
Functions Description
emplace_hint Construct and insert new elements into the map by hint.
Observers
Functions Description
Operations
Functions Description
Allocator
Functions Description
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.
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
Parameter
key: The key data type 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:
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
Iterators
Functions Description
Capacity
Functions Description
Modifiers
Functions Description
emplace_hint Construct and insert new elements into the multimap by hint.
Observers
Functions Description
Operations
Functions Description
Allocator
Functions Description
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.
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.
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:
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
cbegin Returns a const iterator pointing to the first element in the map.
Capacity
Functions Description
Element Access
Functions Description
Modifiers
Functions Description
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
Operations
Functions Description
Allocator
Functions Description
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.
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.
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
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.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call,
we don't know the internal processing.
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.
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 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.
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. }
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
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
Output:
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.
Default constructor
Parameterized 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:
#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:
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.
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
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++.
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:
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.
It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.
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:
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.
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:
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:
C++ Enumeration
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.
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
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.
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
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
Output:
Eating...
Barking...
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?
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.
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:
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.
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.
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...
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 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
Function overloading
Operators overloading
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.
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
The advantage of Operators overloading is to perform different operations on the same operand.
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:
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.
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 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.
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:
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.
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:
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.
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:
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.
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++
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:
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:
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:
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
void swap(string& str) It is used to swap the values of two string objects.
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_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_not_of(string& str,int It searches for the last character that does not match with the specified
pos) sequence.
void push_back(char ch) It adds a new character ch at the end of the string.
void shrink_to_fit() It reduces the capacity and makes it equal to the size of the string.
allocator_type get_allocator(); It returns the allocated object associated with the string.
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.
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.
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.
Output:
Output:
The new exception can be defined by overriding and inheriting exception class functionality.
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:
Output:
Note: In above example what() is a public method provided by the exception class. It is used to return
the cause of an exception.
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:
fstream It is used to create files, write information to files, and read information from files.
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:
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.
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:
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.
class Distance {
private:
int meter;
public:
Distance(): meter(0){ }
};
//function definition
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.
#include
class b
public:
void display()
};
class d:public b
{
public:
void display()
void show()
};
int main()
b B;
b *ptr;
ptr->show();
ptr->show();
Program Output:
P points to base:
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.
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.
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.
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:
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;
#include <iostream>
int main()
*val = 38184.26;
delete val;
#include <iostream>
class stud {
public:
stud()
~stud()
};
int main()
delete[] S;
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;
Example:
'};
or
char greeting[] = "Cloud";
Example:
#include <iostream>
int main ()
#include <iostream>
int main ()
system("pause");
return 0;
'};
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 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).
'};
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:
C++ supports a wide range of functions that manipulate null-terminated strings. These are:
Exceptional handling-
It's very rare that a large program or software works correctly the first time. It might have errors.
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.
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:
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.
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.
#include<iostream>
int main()
try {
throw 6;
}
catch (int a) {
Example:
#include<iostream>
if (var2 == 0) {
int main()
int a = 30;
int b = 0;
double d = 0;
try {
d = division(a, b);
return 0;
Example:
Division by zero.
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.
Output:
Output:
The new exception can be defined by overriding and inheriting exception class functionality.
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:
Output:
Note: In above example what() is a public method provided by the exception class. It is used to return
the cause of an exception.