Full C++
Full C++
Full C++
Introduction
C++ Tutorial
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.
File: main.cpp
1. #include <iostream>
2. using namespace std;
3. int main() {
4. cout << "Hello C++ Programming";
5. return 0;
6. }
What is C++
C++ is a general purpose, case-sensitive, free-form programming language that supports
object-oriented, procedural and generic programming.
C++ is a middle-level language, as it encapsulates both high and low level language
features.
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
2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
outside users.
10 C does not provide the feature of C++ supports the feature of namespace.
) namespace.
It was develop for adding a feature of OOP (Object Oriented Programming) in C without
significantly changing the C component.
Let's see the programming languages that were developed before C++ language.
1. Simple
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
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.
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. }
getch() The getch() function asks for a single character. Until you press any key, it
blocks the screen.
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
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. }
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
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.
<iomanip> It is used to declare services useful for performing formatted I/O, such
as setprecision and setw.
<fstream> It is used to declare services for user-controlled file processing.
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:
Enter your age: 22
Your age is: 22
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:
It is a way to represent memory location through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:
1. type variable_list;
1. int x;
2. float y;
3. char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
1. int x=5,b=10; //declaring 2 variable of integer type
2. float f=30.8;
3. char c='A';
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;
Invalid variable names:
int 4; int x y; int double;
The memory size of basic data types may change according to 32 or 64 bit operating
system.
Let's see the basic data types. It size is given according to 32 bit OS.
Data Types Memory Size Range
float 4 byte
double 8 byte
A list of 30 Keywords in C++ Language which are not available in C language are
given below.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Misc Operator
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and
next. The associativity specifies the operators direction to be evaluated, it may be left to
right or right to left.
int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before
+ (additive operator).
C++
CONTROL STATEMENT
C++ if-else
In C++ programming, if statement is used to test the condition. There are various types of
if statements in C++.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C++ IF Statement
The C++ if statement tests the condition. It is executed if condition is true.
1. if(condition){
2. //code to be executed
3. }
C++ If Example
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. int num = 10;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number";
9. }
10. return 0;
11. }
Output:/p>
It is even number
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
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.
1. for(initialization; condition; incr/decr){
2. //code to be executed
3. }
Output:
1
2
3
4
5
6
7
8
9
10
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:
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:
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c
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:
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:
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:
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
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:
C++ Comments
The C++ comments are statements that are not executed by the compiler. The comments
in C++ programming can be used to provide explanation of the code, variable, method or
class. By the help of comments, you can hide the program code also.
1. #include <ostream>
2. using namespace std;
3. int main()
4. {
5. /* declare and
6. print variable in C++. */
7. int x = 35;
8. cout<<x<<"\n"; //this is single line coment
9. }
Output:
35
C++
FUNCTIONS
C++ Functions
The function in C++ language is also known as procedure or subroutine in other
programming languages.
To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions in C
There are many advantages of functions.
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.
2) Code optimization
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.
Declaration of a function
The syntax of creating function in C++ language is given below:
1. return_type function_name(data_type parameter...)
2. {
3. //code to be executed
4. }
C++ Function Example
Let's see the simple example of C++ function.
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
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:
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 not Changes made inside the function is
reflected on other functions reflected outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The
function which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is known as
tail recursion. In tail recursion, we generally call the same function with return
statement.
1. recursionfunction(){
2. recursionfunction(); //calling self function
3. }
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:
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.
It is recommended to use register variable only for quick access such as in counter.
Note: We can't get the address of register variable.
1. register int counter=0;
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
C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements
that have contiguous memory location.
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.
Advantages of C++ Array
o Code Optimization (less code)
o Random Access
2.
3. Multidimensional 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
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. }
1. functionname(arrayname); //passing array to function
C++ Passing Array to Function Example: print array
elements
Let's see an example of C++ function which prints the array elements.
1. #include <iostream>
2. using namespace std;
3. void printArray(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 10, 20, 30, 40, 50 };
7. int arr2[5] = { 5, 15, 25, 35, 45 };
8. printArray(arr1); //passing array to function
9. printArray(arr2);
10. }
11. void printArray(int arr[5])
12. {
13. cout << "Printing array elements:"<< endl;
14. for (int i = 0; i < 5; i++)
15. {
16. cout<<arr[i]<<"\n";
17. }
18. }
Output:
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
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
Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).
1. int ∗ a; //pointer to int
2. char ∗ c; //pointer to char
Pointer Example
Let's see the simple example of using pointers printing the address and value.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int number=30;
6. int ∗ p;
7. p=&number;//stores the address of number variable
8. cout<<"Address of number variable is:"<<&number<<endl;
9. cout<<"Address of p variable is:"<<p<<endl;
10. cout<<"Value of p variable is:"<<*p<<endl;
11. return 0;
12. }
Output
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
Value of p variable is:30
Output
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.
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.
Advantage of OOPs over Procedure-oriented
programming language
1. OOPs makes development and maintenance easier where as in Procedure-
oriented programming language it is not easy to manage if code grows as project
size grows.
3. OOPs provide ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming language.
C++ Object
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.
1. Student s1; //creating an object of Student
In this example, Student is the type and s1 is the reference variable that refers to the instance of
Student class.
C++ Class
In C++, object is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
15. }
Output:
201
Sonoo Jaiswal
C++ Class Example: Initialize and Display data through
method
Let's see another example of C++ class where we are initializing and displaying object through
method.
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }
Output:
201 Sonoo
202 Nakul
C++ Class Example: Store and Display Employee
Information
Let's see another example of C++ class where we are storing and displaying employee
information using method.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }
Output:
o Default constructor
o 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:
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.
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ this Pointer
In C++ programming, this is a keyword that refers to the current instance of the class. There
can be 3 main usage of this keyword in C++.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}
Output: 101 Sonoo 890000
102 Nakul 59000
C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C++, static can be field, method, constructor, class,
properties, operator and event.
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:
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
Enum in C++ is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum
constants are static and final implicitly.
C++ Enums can be thought of as classes that have fixed set of constants.
Points to remember for C++ Enum
o enum improves type safety
o enum may implement many interfaces but cannot extend any class because it internally
extends Enum class
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
For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.
Declaration of friend function in C++
1. class class_name
2. {
3. friend data_type function_name(argument/s);
4. };
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }
Output:
Length of box: 10
C++
INHERTANCE
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or modify
the attributes and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }
Output:
Salary: 60000
Bonus: 5000
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
19. d1.bark();
20. return 0;
21. }
Output:
Eating...
Barking...
C++ Multi Level Inheritance Example
When one class inherits another class which is further inherited by another class, it is known
as multi level inheritance in C++. Inheritance is transitive so the last derived class acquires
all the members of all its base classes.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }
30. Output:
Eating...Barking? Weeping?
C++ Aggregation (HAS-A Relationship)
In C++, aggregation is a process in which one class defines another class as any entity
reference. It is another way to reuse the class. It is a form of association that represents
HAS-A relationship.
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:
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 with Data
Members
Runtime Polymorphism can be achieved by data members in C++. Let's see an
example where we are accessing the field by reference variable which refers to the
instance of derived class.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. string color = "Black";
6. };
7. class Dog: public Animal
8. {
9. public:
10. string color = "Grey";
11. };
12. int main(void) {
13. Animal d= Dog();
14. cout<<d.color;
15. }
Output:
Black
C++ Overloading (Function and Operator)
If we create two or more members having same name but different in number or
type of parameter, it is known as C++ overloading. In C++, we can overload:
o methods,
o constructors, and
o indexed properties
o Function overloading
o Operators overloading
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
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:
Output:
Eating bread...
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:
1. Abstract class
2. Interface
Abstract class and interface both can have abstract methods which are necessary for
abstraction.
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:
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:
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
C++
Exception Handling
C++ Exception Handling
Exception Handling in C++ is a process to handle runtime errors. We perform exception
handling so the normal flow of the application can be maintained even after runtime errors.
In C++, exception is an event or object which is thrown at runtime. All exceptions are
derived from std::exception class. It is a runtime error which can be handled. If we don't
handle the exception, it prints exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed
even after exception.
Exception Description
o try
o catch, and
o throw
Moreover, we can create user-defined exception which we will learn in next chapters.
C++ try/catch
In C++ programming, exception handling is performed using try/catch statement. The C+
+ try block is used to place the code that may occur exception. The catch block is used to
handle the exception.
Output:
Output:
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.
C++
Files and Streams
C++ Files and Streams
In C++ programming we are using the iostream standard library, it
provides cin and coutmethods for reading from input and writing to output
respectively.
To read and write from a file we are using the standard C++ library called fstream. Let
us see the data types define in fstream library is:
Data Description
Type
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: