C++ Concept
C++ Concept
C++ tutorial provides basic and advanced concepts of C++. Our C++ tutorial is designed for
beginners and professionals.
Our C++ tutorial includes all topics of C++ such as first example, control statements, objects
and classes, inheritance, constructor, destructor, this, static, polymorphism, abstraction,
abstract class, interface, namespace, encapsulation, arrays, strings, exception handling, File
IO, etc.
What is C++
C++ is a middle-level language, as it encapsulates both high and low level language features.
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
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++ Program
In this tutorial, all C++ programs are given with C++ compiler so that you can easily change
the C++ program code.
File: main.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello C++ Programming";
return 0;
}
C vs C++
No. C C++
1) C follows the procedural C++ is multi-paradigm. It supports
style 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 C++ supports the feature of
of namespace. namespace.
11) Exception handling is not easy C++ provides exception handling
in C. It has to perform using using Try and Catch block.
other functions.
C++ history
History of C++ language is interesting to know. Here we are going to discuss brief history
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.
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.
Unlike assembly language, c programs can be executed in many machines with little bit or no
change. But it is not platform-independent.
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.
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
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++ 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. }
void main() The main() function is the entry point of every program in C++ language.
The void keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it blocks
the screen.
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.
Let us see the common header files used in C++ programming are:
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
#include <iostream>
using namespace std;
int main( ) {
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}
Output:
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.
#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
Output:
The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.
#include <iostream>
using namespace std;
int main( ) {
cout << "C++ Tutorial";
cout << " Javatpoint"<<endl;
cout << "End of line"<<endl;
}
Output:
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.
type variable_list;
The example of declaring variable is given below:
int x;
float y;
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.
int a;
int _ab;
int a30;
Invalid variable names:
int 4;
int x y;
int double;
character etc.
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.
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.
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
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.
1. int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before +
(additive operator).
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
1. if(condition){
2. //code to be executed
3. }
C++ If Example
#include <iostream>
using namespace std;
int main () {
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.
if(condition){
//code if condition is true
}else{
//code if condition is false
}
C++ If-else Example
#include <iostream>
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0)
{
cout<<"It is even number"<<endl;
}
else
{
cout<<"It is odd number"<<endl;
}
return 0;
}
The C++ if-else-if ladder statement executes one condition from multiple statements.
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}
C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like if-else-
if ladder statement in C++.
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched;
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
case 20: cout<<"It is 20"; break;
case 30: cout<<"It is 30"; break;
default: cout<<"Not 10, 20 or 30"; break;
}
}
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.
#include <iostream>
using namespace std;
int main() {
for(int i=1;i<=10;i++){
cout<<i <<"\n";
}
}
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
#include <iostream>
int main () {
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
cout<<i<<" "<<j<<"\n";
}
}
1. }
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:
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
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:
11
12
13
21
22
23
31
32
33
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:
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:
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
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:
11
12
13
21
22
23
31
32
33
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);
1. #include <iostream>
2. using namespace std;
3. int main() {
4. do{
5. cout<<"Infinitive do-while Loop";
6. } while(true);
7. }
Output:
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:
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.
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:
11
12
13
21
31
32
33
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;
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 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:
11
12
13
21
23
31
32
33
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.
#include <iostream>
using namespace std;
int main()
{
ineligible:
cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age;
if (age < 18){
goto ineligible;
}
else
{
cout<<"You are eligible to vote!";
}
}
Output:
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.
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
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.
o Fixed size
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
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
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
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:
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:
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:
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.
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:"
255
403
918
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
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
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
The major purpose of C++ programming is to introduce the concept of object orientation to
the C programming language.
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
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.
class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
Let's see another example of C++ class where we are initializing and displaying object
through method.
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main() {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
return 0;
}
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. }
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.
o Default constructor
o Parameterized constructor
C++ Default Constructor
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
#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;
}
C++ Destructor
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.
Let's see an example of constructor and destructor in C++ which is called automatically.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Let's see the example of this keyword in C++ that refers to the fields of current class.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}
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.
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.
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name; //data member(also instance variable)
static float rateOfInterest;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
}
void display()
{
cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;
}
};
float Account::rateOfInterest=6.5;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Employee
Account a2=Account(202, "Nakul"); //creating an object of Employee
a1.display();
a2.display();
return 0;
}
Let's see another example of static keyword in C++ which counts the objects.
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name;
static int count;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
count++;
}
void display()
{
cout<<accno<<" "<<name<<endl;
}
};
int Account::count=0;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Account
Account a2=Account(202, "Nakul");
Account a3=Account(203, "Ranjana");
a1.display();
a2.display();
a3.display();
cout<<"Total Objects are: "<<Account::count;
return 0;
}
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.
Let's see a simple example of struct Rectangle which has two data members width and height.
#include <iostream>
using namespace std;
struct Rectangle
{
int width, height;
};
int main(void) {
struct Rectangle rec;
rec.width=8;
rec.height=5;
cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;
return 0;
}
Let's see another example of struct where we are using constructor to initialize data and
method to calculate area of rectangle.
#include <iostream>
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.
Let's see the simple example of enum data type used in C++ program.
#include <iostream>
using namespace std;
enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
int main()
{
week day;
day = Friday;
cout << "Day: " << day+1<<endl;
return 0;
}
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.
class class_name
{
friend data_type function_name(argument/s);
};
Let's see the simple example of C++ friend function used to print the length of a box.
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and behaviors
of its parent object automatically. In such way, you can reuse, extend or modify the attributes
and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called base class and the
class whose members are inherited is called derived class. The base class is the specialized
class for the derived class.
Code reusability: Now you can reuse the members of your parent class. So, there is no need
to define the member again. So less code is required in the class.
When one class inherits another class, it is known as single level inheritance. Let's see the
example of single level inheritance which inherits the fields only.
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
In the above example, Employee is the base class and Programmer is the derived class.
Let's see another example of inheritance in C++ which inherits methods only.
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
}
};
int main(void) {
Dog d1;
d1.eat();
d1.bark();
return 0;
}
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.
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.
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.
#include <iostream>
using namespace std;
class Address {
public:
string addressLine, city, state;
Address(string addressLine, string city, string state)
{
this->addressLine = addressLine;
this->city = city;
this->state = state;
}
};
class Employee
{
private:
Address* address; //Employee HAS-A Address
public:
int id;
string name;
Employee(int id, string name, Address* address)
{
this->id = id;
this->name = name;
this->address = address;
}
void display()
{
cout<<id <<" "<<name<< " "<<
address->addressLine<< " "<< address->city<< " "<<address->state<<endl;
}
};
int main(void) {
Address a1= Address("C-146, Sec-15","Noida","UP");
Employee e1 = Employee(101,"Nakul",&a1);
e1.display();
return 0;
}
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.
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
Let's see another example of runtime polymorphism in C++ where we are having two derived
classes.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw(){
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape
{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main(void) {
Shape *s;
Shape sh;
Rectangle rec;
Circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=○
s->draw();
}
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.
#include <iostream>
using namespace std;
class Animal {
public:
string color = "Black";
};
class Dog: public Animal
{
public:
string color = "Grey";
};
int main(void) {
Animal d= Dog();
cout<<d.color;
}
C++ Overloading (Function and Operator)
If we create two or more members having same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
o methods,
o constructors, and
o indexed properties
o Function overloading
o Operators 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.
Let's see the simple example of function overloading where we are changing number of
arguments of add() method.
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C;
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
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.
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++()
{
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
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.
Let's see a simple example of Function overriding in C++. In this example, we are overriding
the eat() function.
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
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.
In late binding function call is resolved during runtime. Therefore compiler determines the
type of object at runtime, and then binds the function call.
Let's see the simple example of C++ virtual function used to invoked the derived class in a
program.
#include <iostream>
using namespace std;
class A
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
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.
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.
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void draw()=0;
};
class Rectangle : Shape
{
public:
void draw()
{
cout < <"drawing rectangle..." < <endl;
}
};
class Circle : Shape
{
public:
void draw()
{
cout <<"drawing circle..." < <endl;
}
};
int main( ) {
Rectangle rec;
Circle cir;
rec.draw();
cir.draw();
return 0;
}
In C++ program if we implement class with private and public members then it is an example
of data abstraction.
#include <iostream>
using namespace std;
class Sum
{
private: int x, y, z;
public:
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two number is: "<<z<<endl;
}
};
int main()
{
Sum sm;
sm.add();
return 0;
}
C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to handle the
application.
In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.
Let's see the simple example of namespace which include variable and functions.
#include <iostream>
using namespace std;
namespace First {
void sayHello() {
cout<<"Hello First Namespace"<<endl;
}
}
namespace Second {
void sayHello() {
cout<<"Hello Second Namespace"<<endl;
}
}
int main()
{
First::sayHello();
Second::sayHello();
return 0;
}
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.
#include <iostream>
using namespace std;
namespace First
{
void sayHello(){
cout << "Hello First Namespace" << endl;
}
}
namespace Second{
void sayHello(){
cout << "Hello Second Namespace" << endl;
}
}
using namespace First;
int main () {
sayHello();
return 0;
}
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.
#include <iostream>
using namespace std;
int main( ) {
string s1 = "Hello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
Let's see the simple example of string comparison using strcmp() function.
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char key[] = "mango";
char buffer[50];
do {
cout<<"What is my favourite fruit? ";
cin>>buffer;
} while (strcmp (key,buffer) != 0);
cout<<"Answer is correct!!"<<endl;
return 0;
}
C++ String Concat Example
Let's see the simple example of string concatenation using strcat() function.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
cout << "Enter the buffer string: ";
cin.getline(buffer, 25);
strcat(key, buffer);
cout << "Key = " << key << endl;
cout << "Buffer = " << buffer<<endl;
return 0;
}
Let's see the simple example of copy the string using strcpy() function.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
strcpy(buffer, key);
cout << "Key = "<< key << endl;
cout << "Buffer = "<< buffer<<endl;
return 0;
}
Let's see the simple example of finding the string length using strlen() function.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char ary[] = "Welcome to C++ Programming";
cout << "Length of String = " << strlen(ary)<<endl;
return 0;
}
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
len,string& str) begins at character position pos and spans
len characters.
string& append(const string& It adds new characters at the end of
str) 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 It is used to find the string specified in
n) the parameter.
int find_first_of(string& str,int It is used to find the first occurrence of
pos,int n) the specified sequence.
int find_first_not_of(string& It is used to search the string for the first
str,int pos,int n ) character that does not match 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
pos,int n) character of specified sequence.
int find_last_not_of(string& It searches for the last character that does
str,int pos) not match with the specified sequence.
string& insert() It inserts a new character before the
character indicated by the position 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 It points to the last character of the string.
crbegin()
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.
char* c_str() It returns pointer to an array that contains
null terminated sequence of 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.
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.
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.
o try
o catch, and
o throw
C++ try/catch
#include <iostream>
#include <iostream>
using namespace std;
float division(int x, int y) {
if( y == 0 ) {
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
}catch (const char* e) {
cerr << e << endl;
}
return 0;
}
C++ User-Defined Exceptions
The new exception can be defined by overriding and inheriting exception class functionality.
Let's see the simple example of user-defined exception in which std::exception class is used
to define the exception.
#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception{
public:
const char * what() const throw()
{
return "Attempted to divide by zero!\n";
}
};
int main()
{
try
{
int x, y;
cout << "Enter the two numbers : \n";
cin >> x >> y;
if (y == 0)
{
MyException z;
throw z;
}
else
{
cout << "x / y = " << x/y << endl;
}
}
catch(exception& e)
{
cout << e.what();
}
}
Note: In above example what() is a public method provided by the exception class. It is used
to return the cause of an exception.
To read and write from a file we are using the standard C++ library called fstream. Let us see
the data types define in fstream library is:
Data Description
Type
fstream It is used to create files, write information to files, and read
information from files.
ifstream It is used to read information from files.
ofstream It is used to create files and write information to the files.
Let's see the simple example of writing to a text file testout.txt using C++ FileStream
programming.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to javaTpoint.\n";
filestream << "C++ Tutorial.\n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}
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.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}
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:
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.
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char input[75];
ofstream os;
os.open("testout.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
os << input << endl;
cout << "Please Enter your age: ";
cin >> input;
cin.ignore();
os << input << endl;
os.close();
ifstream is;
string line;
is.open("testout.txt");
cout << "Reading from a text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}
C++ Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming. Generic
programming is a technique where generic types are used as parameters in algorithms so that
they can work for a variety of data types.
o Function templates
o Class templates
Function Templates:
We can define a template for a function. For example, if we have an add() function, we can
create versions of the add function for adding the int, float or double type values.
Class Template:
We can define a template for a class. For example, a class template can be created for the
array class that can accept the array of various types such as int array, float array or double
array.
Function Template
o Generic functions use the concept of a function template. Generic functions define a
set of operations that can be applied to the various types of data.
o The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
o For example, Quick sorting algorithm is implemented using a generic function, it can
be implemented to an array of integers or array of floats.
o A Generic function is created by using the keyword template. The template defines
what function will do.
Syntax of Function Template
template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Where Ttype: It is a placeholder name for a data type used by the function. It is used within the fu
nction definition. It is only a placeholder that the compiler will automatically replace this placeholder
with the actual data type.
#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
In the above example, we create the function template which can perform the addition
operation on any type either it can be integer, float or double.
We can use more than one generic type in the template function by using the comma to
separate the list.
Syntax
#include <iostream>
1. using namespace std;
template<class X,class Y> void fun(X a,Y b)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(15,12.3);
return 0;
}
In the above example, we use two generic types in the template function, i.e., X and Y.
We can overload the generic function means that the overloaded template functions can differ
in the parameter list.
#include <iostream>
using namespace std;
template<class X> void fun(X a)
{
std::cout << "Value of a is : " <<a<< std::endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
std::cout << "Value of b is : " <<b<< std::endl;
std::cout << "Value of c is : " <<c<< std::endl;
}
int main()
{
fun(10);
fun(20,30.5);
return 0;
}
Generic functions perform the same operation for all the versions of a function except the
data type differs. Let's see a simple example of an overloaded function which cannot be
replaced by the generic function as both the functions have different functionalities.
Let's understand this through a simple example:
#include <iostream>
using namespace std;
void fun(double a)
{
cout<<"value of a is : "<<a<<'\n';
}
void fun(int b)
{
if(b%2==0)
{
cout<<"Number is even";
}
else
{
cout<<"Number is odd";
}
int main()
{
fun(4.6);
fun(6);
return 0;
}
In the above example, we overload the ordinary functions. We cannot overload the generic
functions as both the functions have different functionalities. First one is displaying the value
and the second one determines whether the number is even or not.
CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a class uses
the concept of Template, then the class is known as generic class.
Syntax
template<class Ttype>
class class_name
{
.
.
}
Ttype is a placeholder name which will be determined when the class is instantiated. We can define
more than one generic data type using a comma-separated list. The Ttype can be used inside the
class body.
class_name<type> ob;
type: It is the type of the data that the class is operating on.
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
}
};
int main()
{
A<int> d;
d.add();
return 0;
}
We can use more than one generic data type in a class template, and each generic data type is
separated by the comma.
Syntax
int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}
The template can contain multiple arguments, and we can also use the non-type arguments In
addition to the type T argument, we can also use other types of arguments such as strings,
function names, constant expression and built-in types. Let' s see the following example:
void display()
{
for(int i=0;i<size;i++)
{
std::cout << arr[i] << " ";
}
}
};
int main()
{
A<int,10> t1;
t1.insert();
t1.display();
return 0;
}
Points to Remember
C++ Iterators
Iterators are just like pointers used to access the container elements.
Important Points:
o Iterators are used to traverse from one element to another element, a process is known
as iterating through the container.
o The main advantage of an iterator is to provide a common interface for all the
containers type.
o Iterators make the algorithm independent of the type of the container used.
o Iterators provide a generic approach to navigate through the elements of a container.
Syntax
<ContainerType> :: iterator;
<ContainerType> :: const_iterator;
o Operator (*) : The '*' operator returns the element of the current position pointed by
the iterator.
o Operator (++) : The '++' operator increments the iterator by one. Therefore, an
iterator points to the next element of the container.
o Operator (==) and Operator (!=) : Both these operators determine whether the two
iterators point to the same position or not.
o Operator (=) : The '=' operator assigns the iterator.
Iterators can be smart pointers which allow to iterate over the complex data structures. A
Container provides its iterator type. Therefore, we can say that the iterators have the common
interface with different container type.
The container classes provide two basic member functions that allow to iterate or move
through the elements of a container:
o begin(): The begin() function returns an iterator pointing to the first element of the
container.
o end(): The end() function returns an iterator pointing to the past-the-last element of
the container.
#include <iostream>
#include<iterator>
#include<vector>
std::vector<int> v{1,2,3,4,5};
vector<int>::iterator itr;
for(itr=v.begin();itr!=v.end();itr++)
return 0;
Iterator Categories
o Input Iterator
o Output Iterator
o Forward Iterator
o Bidirectional Iterator
o Random Access Iterator
Input Iterator: An input iterator is an iterator used to access the elements from the container,
but it does not modify the value of a container.
o Increment operator(++)
o Equal operator(==)
o Not equal operator(!=)
o Dereference operator(*)
Output Iterator: An output iterator is an iterator used to modify the value of a container, but
it does not read the value from a container. Therefore, we can say that an output iterator is
a write-only iterator.
o Increment operator(++)
o Assignment operator(=)
Forward Iterator: A forward iterator is an iterator used to read and write to a container. It is
a multi-pass iterator.
o Increment operator(++)
o Assignment operator(=)
o Equal operator(=)
o Not equal operator(!=)
o Increment operator(++)
o Assignment operator(=)
o Equal operator(=)
o Not equal operator(!=)
o Decrement operator(--)
Random Access Iterator: A Random Access iterator is an iterator provides random access
of an element at an arbitrary location. It has all the features of a bidirectional iterator plus it
adds one more feature, i.e., pointer addition and pointer subtraction to provide random access
to an element.
Providers Of Iterators
Disadvantages of iterator
o If we want to move from one data structure to another at the same time, iterators won't
work.
o If we want to update the structure which is being iterated, an iterator won?t allow us
to do because of the way it stores the position.
o If we want to backtrack while processing through a list, the iterator will not work in
this case.
Advantages of iterator
#include <iostream>
#include<vector>
#include<iterator>
int main()
vector<int> v{1,2,3,4,5};
vector<int>::iterator itr;
cout<<v[i]<<" ";
cout<<'\n';
for(itr=v.begin();itr!=v.end();itr++) // Traversal by using an iterator.
cout<<*itr<<" ";
v.push_back(10);
cout<<'\n';
for(int i=0;i<6;i++)
cout<<v[i]<<" ";
cout<<'\n';
for(itr=v.begin();itr!=v.end();itr++)
cout<<*itr<<" ";
return 0;
o Code Reusability: A code can be reused if we use iterators. In the above example, if
we replace vector with the list, and then the subscript operator[] would not work to
access the elements as the list does not support the random access. However, we use
iterators to access the elements, then we can also access the list elements.
o Dynamic Processing: C++ iterators provide the facility to add or delete the data
dynamically.
#include <iostream>
#include<vector>
#include<iterator>
vector<int>::iterator itr;
v.insert(v.begin()+1,10);
for(itr=v.begin();itr!=v.end();itr++)
cout<<*itr<<" ";
return 0;
The most important difference between the Random access iterator and other iterators is
that random access iterator requires '1' step to access an element while other iterators
require 'n' steps.
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.
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
vector<object_type> v1;
Example
Let's see a simple example.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> v1;
v1.push_back("javaTpoint ");
v1.push_back("tutorial");
for(vector<string>::iterator itr=v1.begin();itr!=v1.end();++itr)
cout<<*itr;
return 0;
}
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.
Syntax
1. vector<object_type> v;
2. v.at(k) ;
Parameter
Return value
Example
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v1{1,2,3,4};
for(int i=0;i<v1.size();i++)
cout<<v1.at(i);
return 0;
}
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.
deque<object_type> deque_name;
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.