Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 132

C++ Programming

Syllabus Content
C++ Programming
 C++Overview
 C++ Characteristics
 Object- Oriented Terminology
 Polymorphism
 Object- Oriented Paradigm
 Abstract Data Type
 I/S Services
 Standard Template Library
 Standard Compliance
Functions and Variables
 Functions: Declaration and Definition
 Variables: Definition, Declaration and Scope
 Variables: Dynamic Creation and Derived Data
 Arrays and Strings in C++
 Qualifiers
Classes in C++
 Defining Classes in C++
 Classes in Encapsulation
 Member Functions
 Instantiating and Using Classes
 Using Constructors
 Multiple Constructors and Initialization Lists
 Using Destructors to Destroy Instances
 Friendship
Operator Overloading
 Operator Overloading
 Working with Overload Operator Methods
Initialization and Assignment
 Initialization V/s Assignment
 The Copy Constructors
 Assigning Values
 Specialized Constructors and Methods
 Constant and Static Class Members
Syllabus Content
Storage Management
 Memory Allocation
 Dynamic Allocation: New and Delete
Inheritance
 Overview of Inheritance
 Defining Base and Derived Classes
 Constructor and Destructor calls

Polymorphism
 Overview of Polymorphism
Input and Output in C ++ Programs
 Standard Streams
 Manipulators
 Unformatted Input and Output
 File Input and Output
Exceptions
 Exceptions
 Inheritance and Exceptions
 Exception Hierarchies
 Inside and Exception Handler
Templates
 Template Overview
 Customizing a Template Method
 Standard Template Library Containers
C++ is a middle-level programming language developed by Bjarne Stroustrup
starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows,
Mac OS, and the various versions of UNIX.

Why to Learn C++


C++ is a MUST for students and working professionals to become a great Software
Engineer. I will list down some of the key advantages of learning C++:
 C++ is very close to hardware, so you get a chance to work at a low level
which gives you lot of control in terms of memory management, better
performance and finally a robust software development.
 C++ programming gives you a clear understanding about Object Oriented
Programming. You will understand low level implementation of polymorphism
when you will implement virtual tables and virtual table pointers, or dynamic
type identification.
 C++ is one of the every green programming languages and loved by millions
of software developers. If you are a great C++ programmer then you will
never sit without work and more importantly you will get highly paid for your
work.
 C++ is the most widely used programming languages in application and
system programming. So you can choose your area of interest of software
development.
 C++ really teaches you the difference between compiler, linker and loader,
different data types, storage classes, variable types their scopes etc.

Hello World using C++


Just to give you a little excitement about C++ programming, I'm going to give you a
small conventional C++ Hello World program

#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
Output:
Hello World
What is C++
C++ is a general purpose, case-sensitive, free-form programming language that supports object-
oriented, procedural and generic programming.

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

Object-Oriented Programming (OOPs)


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

1. Inheritance

2. Polymorphism

3. Encapsulation

4. Abstraction

C++ Standard Libraries


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

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

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

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

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

o Window application

o Client-Server application

o Device drivers

o Embedded firmware etc


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.

Real Life Example Of Polymorphism


Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a classroom,
mother or daughter in a home and customer in a market. Here, a single person is behaving
differently according to the situations.

There are two types of polymorphism in C++:

o Compile time polymorphism: The overloaded functions are invoked by matching the
type and number of arguments. This information is available at the compile time and,
therefore, compiler selects the appropriate function at the compile time. It is achieved by
function overloading and operator overloading which is also known as static binding or
early binding. Now, let's consider the case where function name and prototype is same.

Difference’s b/w compile time and run time


polymorphism.
Compile time Run time
polymorphism polymorphism

The function to be invoked The function to be invoked


is known at the compile is known at the run time.
time.

It is also known as It is also known as


overloading, early binding overriding, Dynamic
and static binding. binding and late binding.

Overloading is a compile Overriding is a run time


time polymorphism where polymorphism where
more than one method is more than one method is
having the same name but having the same name,
with the different number of number of parameters
parameters or the type of and the type of the
the parameters. parameters.

It is achieved by function It is achieved by virtual


overloading and operator functions and pointers.
overloading.

It provides fast execution as It provides slow execution


it is known at the compile as it is known at the run
time. time.

It is less flexible as mainly It is more flexible as all


all the things execute at the the things execute at the
compile time. run time.

C++ Runtime Polymorphism Example


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

// an example without the virtual keyword.

#include <iostream.h>    
#include<conio.h>
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();    
getch();
   return 0;    
}    

Output:

Eating bread...

C++ Run time Polymorphism Example: By using


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

// an example with virtual keyword.

#include <iostream.h>    
#include<conio.h>
using namespace std;    
class Shape {                                        //  base class  
    public:    
virtual void draw(){                             // virtual function  
cout<<"drawing..."<<endl;      
    }        
};     
class Rectangle: public Shape                  //  inheriting Shape class.  
{      
 public:    
 void draw()      
   {      
       cout<<"drawing rectangle..."<<endl;      
    }      
};    
class Circle: public Shape                        //  inheriting Shape class.  
  
{      
 public:    
 void draw()      
   {      
      cout<<"drawing circle..."<<endl;      
   }      
};    
int main(void) {    
    Shape *s;                               //  base class pointer.  
    Shape sh;                               // base class object.  
       Rectangle rec;    
        Circle cir;    
      s=&sh;    
     s->draw();     
        s=&rec;    
     s->draw();      
    s=?    
    s->draw();     
getch();
}    

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.

#include <iostream.h>    
#include<conio.h>
using namespace std;    
class Animal {                                          //  base class declaration.  
    public:    
    string color = "Black";      
};     
class Dog: public Animal                       // inheriting Animal class.  
{      
 public:    
    string color = "Grey";      
};    
int main(void) {    
    Animal d= Dog();      
    cout<<d.color;     
getch();
}    

Output:

Black

C++ OOPs Concepts/Object-Oriented


Paradigm
The major purpose of C++ programming is to introduce the concept of object orientation to the C
programming language.

Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.

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


object-oriented programming language. Smalltalk is considered as the first truly object-oriented
programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

o Object

o Class

o Inheritance

o Polymorphism

o Abstraction

o Encapsulation

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

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

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

Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
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.

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


global data can be accessed from anywhere.

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

Abstract Data Types in C++


Now that we’ve seen the concept of abstract data types (ADTs), we proceed to
examine the mechanisms C++ provides for defining an ADT. Unlike C, C++ allows
the data and functions of an ADT to be defined together.

#include <iostream>
using namespace std;

int main() {
cout << "Hello C++" <<endl;
return 0;
}
Output
Hello C++
Data Abstraction Example
Any C++ program where you implement a class with public and private members is
an example of data abstraction.

#include <iostream>
using namespace std;

class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}

// interface to outside world


void addNum(int number) {
total += number;
}

// interface to outside world


int getTotal() {
return total;
};

private:
// hidden data from outside world
int total;
};

int main() {
Adder a;

a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}

Output
Total 60
C++ Basic Input/Output
The C++ standard libraries provide an extensive set of input/output capabilities
which we will see in subsequent chapters. This chapter will discuss very basic and
most common I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a
device like a keyboard, a disk drive, or a network connection etc. to main memory,
this is called input operation and if bytes flow from main memory to a device like a
display screen, a printer, a disk drive, or a network connection, etc., this is
called output operation.

I/O Library Header Files


There are following header files important to C++ programs −

Sr.No Header File & Function and Description

1 <iostream>
This file defines the cin, cout, cerr and clog objects, which
correspond to the standard input stream, the standard output
stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.

2 <iomanip>
This file declares services useful for performing formatted I/O with
so-called parameterized stream manipulators, such
as setw and setprecision.

3 <fstream>
This file declares services for user-controlled file processing. We
will discuss about it in detail in File and Stream related chapter.

The Standard Output Stream (cout)


The predefined object cout is an instance of ostream class. The cout object is said
to be "connected to" the standard output device, which usually is the display screen.
The cout is used in conjunction with the stream insertion operator, which is written
as << which are two less than signs as shown in the following example.
#include <iostream>

using namespace std;

int main() {
char str[] = "Hello C++";

cout << "Value of str is : " << str << endl;


}
When the above code is compiled and executed, it produces the following result −
Value of str is : Hello C++

The Standard Input Stream (cin)


The predefined object cin is an instance of istream class. The cin object is said to
be attached to the standard input device, which usually is the keyboard. The cin is
used in conjunction with the stream extraction operator, which is written as >> which
are two greater than signs as shown in the following example.
#include <iostream>

using namespace std;

int main() {
char name[50];

cout << "Please enter your name: ";


cin >> name;
cout << "Your name is: " << name << endl;

When the above code is compiled and executed, it will prompt you to enter a name.
You enter a value and then hit enter to see the following result −
Please enter your name: cplusplus
Your name is: cplusplus

The Standard Error Stream (cerr)


The predefined object cerr is an instance of ostream class. The cerr object is said
to be attached to the standard error device, which is also a display screen but the
object cerr is un-buffered and each stream insertion to cerr causes its output to
appear immediately.
The cerr is also used in conjunction with the stream insertion operator as shown in
the following example.
#include <iostream>
using namespace std;

int main() {
char str[] = "Unable to read....";

cerr << "Error message : " << str << endl;


}
When the above code is compiled and executed, it produces the following result −
Error message : Unable to read....

The Standard Log Stream (clog)


The predefined object clog is an instance of ostream class. The clog object is said
to be attached to the standard error device, which is also a display screen but the
object clog is buffered. This means that each insertion to clog could cause its
output to be held in a buffer until the buffer is filled or until the buffer is flushed.
The clog is also used in conjunction with the stream insertion operator as shown in
the following example.
#include <iostream>

using namespace std;

int main() {
char str[] = "Unable to read....";

clog << "Error message : " << str << endl;


}
When the above code is compiled and executed, it produces the following result −
Error message : Unable to read....

C++ STL Standard Template Library


The C++ STL (Standard Template Library) is a powerful set of C++ template
classes to provide general-purpose classes and functions with templates that
implement many popular and commonly used algorithms and data structures like
vectors, lists, queues, and stacks.
At the core of the C++ Standard Template Library are following three well-structured
components –
Sr.No Component & Description

1 Containers
Containers are used to manage collections of objects of a certain kind.
There are several different types of containers like deque, list, vector,
map etc.

2 Algorithms
Algorithms act on containers. They provide the means by which you will
perform initialization, sorting, searching, and transforming of the
contents of containers.

3 Iterators
Iterators are used to step through the elements of collections of objects.
These collections may be containers or subsets of containers.

We will discuss about all the three C++ STL components in next chapter while
discussing C++ Standard Library.
Let us take the following program that demonstrates the vector container (a
C++ Standard Template) which is similar to an array with an exception that it
automatically handles its own storage requirements in case it grows –

#include <iostream>
#include <vector>
using namespace std;

int main() {

// create a vector to store int


vector<int> vec;
int i;

// display the original size of vec


cout << "vector size = " << vec.size() << endl;

// push 5 values into the vector


for(i = 0; i < 5; i++) {
vec.push_back(i);
}

// display extended size of vec


cout << "extended vector size = " << vec.size() << endl;

// access 5 values from the vector


for(i = 0; i < 5; i++) {
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}

// use iterator to access the values


vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4

Here are following points to be noted related to various functions we used in the
above example −
 The push_back( ) member function inserts value at the end of the vector,
expanding its size as needed.
 The size( ) function displays the size of the vector.
 The function begin( ) returns an iterator to the start of the vector.
 The function end( ) returns an iterator to the end of the vector.

Standard compliance in c++ programming

Coding standards
Coding standards are collections of rules and guidelines that determine the
programming style, procedures, and methods for a programming language.

Importance of coding conventions

Without the coding conventions, every individual in a team will settle their
coding styles. It will not be easy to maintain and debug the code in the near
future.

Benefits of coding standards

 Easy team integration

 Increased code quality efficiency and easy for maintaining

 Reduce code complexity

 Reduce development cost

Drawbacks of not having proper coding conventions for a team

Without predefined conditions that all team member should follow can result
in the following:

 Reduced engineers motivation

 Increased development time

 Complex codebase structure

Common Aspects of Coding Standard :

 Naming Conventions: The naming convention is how your


packages, classes methods, variables, etc. should be named.
( eg. camelCase, PascalCase or snake_case)
 File and folder Naming and Organization: This is how your file
and folder should be named and structured

 Formatting and Indentation: the code should be written in a


standardized format and indentation

 Commenting and Documenting: This makes it easy for the


reviewer of your code to better understand codes methods and
declarations

 Classes and Functions: This specifies how classes and


functions should behave.

 Testing: This specifies which approach and tools should be used


to test the codes

C++ Functions
A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main(), and all the most trivial programs can
define additional functions.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program
can call. For example, function strcat() to concatenate two strings,

Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}

A C++ function definition consists of a function header and a function body. Here
are all the parts of a function −
 Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
 Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked,
you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
 Function Body − The function body contains a collection of statements that
define what the function does.

Example
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and return the biggest of both

// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );

For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is
required, so following is also valid declaration −
int max(int, int);

Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function at
the top of the file calling the function.

Calling a Function
While creating a C++ function, you give a definition of what the function has to do.
To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called
function. A called function performs defined task and when it’s return statement is
executed or when its function-ending closing brace is reached, it returns program
control back to the main program.

#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2) {
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
While running final executable, it would produce the following result −
Max value is : 200
C++ Variable Types
A variable provides us with named storage that our programs can manipulate. Each
variable in C++ has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and
the set of operations that can be applied to the variable.
There are following basic types of variable in C++ as explained in last chapter −

Sr.No Type & Description

1 bool
Stores either value true or false.

2 char
Typically a single octet (one byte). This is an integer type.

3 int
The most natural size of integer for the machine.

4 float
A single-precision floating point value.

C++ also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Reference, Data
structures, and Classes.
Following section will cover how to define, declare and use various types of
variables.

Variable Definition in C++


A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type, and contains a list of one or
more variables of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double,
bool or any user-defined object, etc., and variable_list may consist of one or more
identifier names separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; both declares and defines the variables i, j and k; which instructs
the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows −
type variable_name = value;

Some examples are –

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables is undefined.

Variable Declaration in C++


A variable declaration provides assurance to the compiler that there is one variable
existing with the given type and name so that compiler proceed for further
compilation without needing complete detail about the variable. A variable
declaration has its meaning at the time of compilation only, compiler needs actual
variable definition at the time of linking of the program.
Example
Try the following example where a variable has been declared at the top, but it has
been defined inside the main function −
#include <iostream>
using namespace std;

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {
// Variable definition:
int a, b;
int c;
float f;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c << endl ;

f = 70.0/3.0;
cout << f << endl ;

return 0;
}
When the above code is compiled and executed, it produces the following result −
30
23.3333

Variable Scope in C++


A scope is a region of the program and broadly speaking there are three places,
where variables can be declared −
 Inside a function or a block which is called local variables,
 In the definition of function parameters which is called formal parameters.
 Outside of all functions which is called global variables

Local Variables
Variables that are declared inside a function or block are local variables. They can
be used only by statements that are inside that function or block of code. Local
variables are not known to functions outside their own. Following is the example
using local variables 
#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a, b;
int c;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c;

return 0;
}

Output
30
Global Variables
Global variables are defined outside of all the functions, usually on top of the
program. The global variables will hold their value throughout the life-time of your
program.
#include <iostream>
using namespace std;

// Global variable declaration:


int g;

int main () {
// Local variable declaration:
int a, b;

// actual initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}

Output
30

A program can have same name for local and global variables but value of local
variable inside a function will take preference. For example −
#include <iostream>
using namespace std;

// Global variable declaration:


int g = 20;

int main () {
// Local variable declaration:
int g = 10;

cout << g;

return 0;
}
When the above code is compiled and executed, it produces the following result −
10
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must initialize
it yourself. Global variables are initialized automatically by the system when you
define them as follows −

Data Type Initializer

int 0

char '\0'

float 0

double 0

pointer NULL

Derived Data Types in C++


Data types are means to identify the type of data and associated
operations of handling it. There are three types of data types:
1. Pre-defined DataTypes
2. Derived Data Types
3. User-defined DataTypes
Derived Data Types

The data-types that are derived from the primitive or built-in datatypes
are referred to as Derived Data Types. These can be of four types
namely:
 Function
 Array
 Pointers
 References
Let’s briefly understand each of the following derived datatypes:
1. Function: A function is a block of code or program-segment
that is defined to perform a specific well-defined task. A
function is generally defined to save the user from writing the
same lines of code again and again for the same input.
Syntax:

FunctionType FunctionName(parameters)
Example:

// C++ program to demonstrate

// Function Derived Type

#include <iostream>

using namespace std;

// max here is a function derived type

int max(int x, int y)

    if (x > y)

        return x;

    else

        return y;

// main is the default function derived type

int main()

    int a = 10, b = 20;

    // Calling above function to

    // find max of 'a' and 'b'

    int m = max(a, b);

    cout << "m is " << m;


    return 0;

Output:
m is 20

Array: An array is a collection of items stored at continuous memory


locations. The idea of array is to represent many instances in one
variable.

Syntax:
DataType ArrayName[size_of_array];
Example:

// C++ program to demonstrate

// Array Derived Type

  

#include <iostream>

using namespace std;

int main()

  
    // Array Derived Type

    int arr[5];

    arr[0] = 5;

    arr[2] = -10;

    // this is same as arr[1] = 2

    arr[3 / 2] = 2;

     arr[3] = arr[0];

    cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3];

    return 0;

Output:
2 -10 5

Pointers: Pointers are symbolic representation of addresses. They


enable programs to simulate call-by-reference as well as to create and
manipulate dynamic data structures. It’s general declaration in C/C++
has the format:
Syntax:
datatype *var_name;
Example:
int *ptr;

ptr points to an address


which holds int data

Example:
// C++ program to illustrate

// Pointers Derived Type

  

#include <bits/stdc++.h>

using namespace std;

  

void geeks()

    int var = 20;

  

    // Pointers Derived Type

    // declare pointer variable

    int* ptr;

  

    // note that data type of ptr

    // and var must be same

    ptr = &var;

  

    // assign the address of a variable

    // to a pointer
    cout << "Value at ptr = "

         << ptr << "\n";

    cout << "Value at var = "

         << var << "\n";

    cout << "Value at *ptr = "

         << *ptr << "\n";

  

// Driver program

int main()

    geeks();

Output:
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20

Reference: When a variable is declared as reference, it becomes an


alternative name for an existing variable. A variable can be declared as
reference by putting ‘&’ in the declaration.
Example:

// C++ program to illustrate


// Reference Derived Type

  

#include <iostream>

using namespace std;

  

int main()

    int x = 10;

  

    // Reference Derived Type

    // ref is a reference to x.

    int& ref = x;

  

    // Value of x is now changed to 20

    ref = 20;

    cout << "x = " << x << endl;

  

    // Value of x is now changed to 30

    x = 30;

    cout << "ref = " << ref << endl;


  

    return 0;

Output:
x = 20
ref = 30

Qualifiers and storage class


Qualifiers and storage class are smaller but important programming concept that
helps to make the quality of a variable more accurate for using that variable within
the program. In this chapter, you will learn about how qualifiers are used with
variables and what the roles of different storage classes in C++ .
A qualifier is a token added to a variable which adds an extra quality, such as
specifying volatility or constant-ness to a variable. They act like an adjective for a
variable. With or without a qualifier, the variable itself still occupies the same amount
of memory, and each bit has the same interpretation or contribution to the
state/value.
Three qualifiers are there in C++. These are:

 const: This is used to define that the type is constant.


 volatile: This is used to define that the type is volatile.
 mutable: applies to non-static class members of the non-reference non-const
type. Mutable members of const classes are modifiable.
Storage classes are used to classify the lifetime and scope of variables. It tells
how storage is allocated for variables and how a variable can be treated by the
compiler; everything depends on these storage classes.

These storage classes are divided into four types. They are:

 Auto Variables
 Register variables
 Static Variables
 Extern Variables
Auto:
This is the C++'s default storage class you have been using or the compiler is
automatically assigning it to the variables.
The keyword used is "auto".

Example:
int var1;          // by default, storage class is auto

auto int var;

register
The register storage class is used to classify local variables that gets stored in the
CPU register instead of primary memory (RAM) which means that the variable has a
maximum size equal to the register size (usually one word) and cannot have the
unary '&' operator applied to it (as it does not have a memory location).

The keyword "register" is used for declaring register variables.


Example of declaration:

Example:
register int var2;

static

The scope of a static variable is local to the function in which it is defined but it
doesn't get terminated when the function execution gets over. In other words, the
static storage class tells the compiler to keep the local variable in existence during
the lifetime of the program instead of destroying it with the end of function scope
 The static modifier may also be applied to global variables.
Example:
static int var3 = 6;

extern
Variables having extern storage class have a global scope. Extern variables are
used when programmers want a variable to be visible outside the file in which it is
declared.

Extern variables do not end until the program execution gets terminated.
Example:
extern int var4; // declaration of variable 'var4'
int var4;          // definition of variable 'var4'

Program for static Storage Class


#include <iostream>

using namespace std;

void fun()

static int i = 6;

i++;

cout << i;

int main()

fun();

fun();

fun();

Classes in C++
The main purpose of C++ programming is to add object orientation to the C
programming language and classes are the central feature of C++ that supports
object-oriented programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation
and methods for manipulating that data into one neat package. The data and
functions within a class are called members of the class.

C++ Class Definitions


When you define a class, you define a blueprint for a data type. This doesn't
actually define any data, but it does define what the class name means, that is,
what an object of the class will consist of and what operations can be performed on
such an object.
A class definition starts with the keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces.

 For example, we defined the Box data type using the keyword class as follows −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

The keyword public determines the access attributes of the members of the class


that follows it. A public member can be accessed from outside the class anywhere
within the scope of the class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.

Define C++ Objects


A class provides the blueprints for objects, so basically an object is created from a
class. We declare objects of a class with exactly the same sort of declaration that
we declare variables of basic types.
Following statements declare two objects of class Box −
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members


The public data members of objects of a class can be accessed using the direct
member access operator (.). Let us try the following example to make the things
clear

#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560

C++ Inheritance
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance
allows us to define a class in terms of another class, which makes it easier to create and maintain an
application.

When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should inherit
the members of an existing class. This existing class is called the base class, and
the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-
A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Base and Derived Classes


A class can be derived from more than one classes, which means it can inherit data
and functions from multiple base classes
A class derivation list names one or more base classes and has the form −
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. 

Consider a base class Shape and its derived class Rectangle as follows –

#include <iostream>

using namespace std;

// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Access Control and Inheritance
A derived class can access all the non-private members of its base class. Thus
base-class members that should not be accessible to the member functions of
derived classes should be declared private in the base class.
We can summarize the different access types according to - who can access them
in the following way −

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

A derived class inherits all base class methods with the following exceptions −

 Constructors, destructors and copy constructors of the base class.


 Overloaded operators of the base class.
 The friend functions of the base class.
Type of Inheritance
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is
commonly used. While using different type of inheritance, following rules are applied

 Public Inheritance − When deriving a class from a public base
class, public members of the base class become public members of the
derived class and protected members of the base class
become protected members of the derived class. A base
class's private members are never accessible directly from a derived class,
but can be accessed through calls to the public and protected members of
the base class.
 Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class
become protected members of the derived class.
 Private Inheritance − When deriving from a private base
class, public and protected members of the base class
become private members of the derived class.
Multiple Inheritance
A C++ class can inherit members from more than one class and here is the
extended syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every
base class and they will be separated by comma as shown above. Let us try the
following example −
#include <iostream>

using namespace std;

// Base class Shape


class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Base class PaintCost


class PaintCost {
public:
int getCost(int area) {
return area * 70;
}
};

// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;
int area;

Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

// Print the total cost of painting


cout << "Total paint cost: $" << Rect.getCost(area) << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Total paint cost: $2450

C++ Overloading (Operator and Function)


C++ allows you to specify more than one definition for a function name or an operator in the same
scope, which is called function overloading and operator overloading respectively.

When you call an overloaded function or operator, the compiler determines the most appropriate
definition to use, by comparing the argument types you have used to call the function or operator with
the parameter types specified in the definitions. The process of selecting the most appropriate
overloaded function or operator is called overload resolution.

Function Overloading in C++


You can have multiple definitions for the same function name in the same scope.
The definition of the function must differ from each other by the types and/or the
number of arguments in the argument list. You cannot overload function
declarations that differ only by return type.
Following is the example where same function print() is being used to print different
data types −
#include <iostream>
using namespace std;

class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;

// Call print to print integer


pd.print(5);

// Call print to print float


pd.print(500.263);

// Call print to print character


pd.print("Hello C++");

return 0;
}

When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Operators Overloading in C++


You can redefine or overload most of the built-in operators available in C++. Thus, a
programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator"
followed by the symbol for the operator being defined. Like any other function, an
overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns
final Box object. Most overloaded operators may be defined as ordinary non-
member functions or as class member functions. In case we define above function
as non-member function of a class then we would have to pass two arguments for
each operand as follows −
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using a
member function.

#include <iostream>
using namespace std;

class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}

// Overload + operator to add two Box objects.


Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Data Encapsulation in C++


Data encapsulation is a mechanism of bundling the data, and the functions that
use them and data abstraction is a mechanism of exposing only the interfaces and
hiding the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation
of user-defined types, called classes. We already have studied that a class can
contain private, protected and public members. By default, all items defined in a
class are private. For example −
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your
program. This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program),
you must declare them after the public keyword. All variables or functions defined
after the public specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and
reduces encapsulation.
#include <iostream>
using namespace std;

class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}

// interface to outside world


void addNum(int number) {
total += number;
}

// interface to outside world


int getTotal() {
return total;
};

private:
// hidden data from outside world
int total;
};

int main() {
Adder a;

a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}
When the above code is compiled and executed, it produces the following result −
Total 60

C++ Class Member Functions


A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object of the
class of which it is a member, and has access to all the members of a class for that
object.
Let us take previously defined class to access the members of the class using a
member function instead of directly accessing them −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
Member functions can be defined within the class definition or separately
using scope resolution operator, : −. Defining a member function within the class
definition declares the function inline, even if you do not use the inline specifier. So
either you can define Volume() function as below −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

double getVolume(void) {
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope
resolution operator (::) as follows −
double Box::getVolume(void) {
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before ::
operator. A member function will be called using a dot operator (.) on a object where
it will manipulate data related to that object only as follows −
Box myBox; // Create an object

myBox.getVolume(); // Call member function for the object


Let us put above concepts to set and get the value of different class members in a
class −

#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

// Member functions declaration


double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};

// Member functions definitions


double Box::getVolume(void) {
return length * breadth * height;
}

void Box::setLength( double len ) {


length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560

Constructors
Constructors are special class members which are called by the
compiler every time an object of that class is instantiated. Constructors
have the same name as the class and may be defined inside or outside
the class definition.
There are 3 types of constructors:
 Default constructors
 Parametrized constructors
 Copy constructors

// C++ program to demonstrate constructors

#include <bits/stdc++.h>

using namespace std;

class Geeks

    public:

    int id;

      

    //Default Constructor

    Geeks()

    {

        cout << "Default Constructor called" << endl; 

        id=-1;

    }

      

    //Parametrized Constructor
    Geeks(int x)

    {

        cout << "Parametrized Constructor called" << endl;

        id=x;

    }

};

int main() {

      

    // obj1 will call Default Constructor

    Geeks obj1;

    cout << "Geek id is: " <<obj1.id << endl;

      

    // obj1 will call Parametrized Constructor

    Geeks obj2(21);

    cout << "Geek id is: " <<obj2.id << endl;

    return 0;

Output:
Default Constructor called
Geek id is: -1
Parametrized Constructor called
Geek id is: 21
A Copy Constructor creates a new object, which is exact copy of the
existing object. The compiler provides a default Copy Constructor to all
the classes.
Syntax:
class-name (class-name &){}

Destructors
Destructor is another special member function that is called by the
compiler when the scope of the object ends.

// C++ program to explain destructors

#include <bits/stdc++.h>

using namespace std;

class Geeks

    public:

    int id;

      

    //Definition for Destructor

    ~Geeks()

    {

        cout << "Destructor called for id: " << id <<endl; 

    }

};
  

int main() 

  {

    Geeks obj1;

    obj1.id=7;

    int i = 0;

    while ( i < 5 )

    {

        Geeks obj2;

        obj2.id=i;

        i++;        

    } // Scope for obj2 ends here

  

    return 0;

  } // Scope for obj1 ends here

Output:
Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7
Multiple Constructors

// C++ program to demonstrate constructor overloading


#include <iostream>
using namespace std;

class Person {
private:
int age;

public:
// 1. Constructor with no arguments
Person() {
age = 20;
}

// 2. Constructor with an argument


Person(int a) {
age = a;
}

int getAge() {
return age;
}
};

int main() {
Person person1, person2(45);

cout << "Person1 Age = " << person1.getAge() << endl;


cout << "Person2 Age = " << person2.getAge() << endl;

return 0;
}

Output

Person1 Age = 20
Person2 Age = 45
2: Constructor overloading

// C++ program to demonstrate constructor overloading


#include <iostream>
using namespace std;

class Room {
private:
double length;
double breadth;

public:
// 1. Constructor with no arguments
Room() {
length = 6.9;
breadth = 4.2;
}

// 2. Constructor with two arguments


Room(double l, double b) {
length = l;
breadth = b;
}
// 3. Constructor with one argument
Room(double len) {
length = len;
breadth = 7.2;
}

double calculateArea() {
return length * breadth;
}
};

int main() {
Room room1, room2(8.2, 6.6), room3(8.2);

cout << "When no argument is passed: " << endl;


cout << "Area of room = " << room1.calculateArea() << endl;

cout << "\nWhen (8.2, 6.6) is passed." << endl;


cout << "Area of room = " << room2.calculateArea() << endl;

cout << "\nWhen breadth is fixed to 7.2 and (8.2) is passed:" << endl;
cout << "Area of room = " << room3.calculateArea() << endl;

return 0;
}

Output

When no argument is passed:


Area of room = 28.98

When (8.2, 6.6) is passed.


Area of room = 54.12

When breadth is fixed to 7.2 and (8.2) is passed:


Area of room = 59.04

C++ Friend Functions


A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class. Even though the prototypes
for friend functions appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or
class template, in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the
class definition with keyword friend as follows −
class Box {
double width;

public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne,
place a following declaration in the definition of class ClassOne −
friend class ClassTwo;
Consider the following program −
#include <iostream>

using namespace std;

class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};

// Member function definition


void Box::setWidth( double wid ) {
width = wid;
}

// Note: printWidth() is not a member function of any class.


void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}

// Main function for the program


int main() {
Box box;

// set box width without member function


box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return 0;
}

When the above code is compiled and executed, it produces the following result −
Width of box : 10

Variable assignment and initialization


Introduction to variables we covered how to define a variable that we can use to
store values. we’ll explore how to actually put values into variables and use those
values.

As a reminder, here’s a short snippet that first allocates a single integer variable
named x, then allocates two more integer variables named y and z:

1 int x; // define an integer variable named x


2 int y, z; // define two integer variables, named y and z

Variable assignment
After a variable has been defined, you can give it a value (in a separate statement) using
the = operator. This process is called copy assignment (or just assignment) for short.
int width; // define an integer variable named width
width = 5; // copy assignment of value 5 into variable width
 
// variable width now has value 5

Copy assignment is named such because it copies the value on the right-hand side of
the = operator to the variable on the left-hand side of the operator. The = operator is
called the assignment operator.

Here’s an example where we use assignment twice:

#include <iostream>
 
int main()
{
int width;
width = 5; // copy assignment of value 5 into variable width
 
// variable width now has value 5
 
width = 7; // change value stored in variable width to 7
 
// variable width now has value 7
 
return 0;
}

Copy Constructor in C+
A copy constructor is a member function that initializes an object using
another object of the same class. A copy constructor has the following
general function prototype: 
ClassName (const ClassName &old_obj);
Following is a simple example of copy constructor. 

#include<iostream>

using namespace std;

class Point
{

private:

    int x, y;

public:

    Point(int x1, int y1) { x = x1; y = y1; }

    // Copy constructor

    Point(const Point &p1) {x = p1.x; y = p1.y; }

    int getX()            {  return x; }

    int getY()            {  return y; }

};

int main()

    Point p1(10, 15); // Normal constructor is


called here

    Point p2 = p1; // Copy constructor is called


here

    // Let us access values assigned by constructors

    cout << "p1.x = " << p1.getX() << ", p1.y = " <<
p1.getY();

    cout << "\np2.x = " << p2.getX() << ", p2.y = "
<< p2.getY();

    return 0;

Output: 
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

When is  copy constructor called? 


In C++, a Copy Constructor may be called in the following cases: 
1. When an object of the class is returned by value. 
2. When an object of the class is passed (to a function) by value as an
argument. 
3. When an object is constructed based on another object of the same
class. 

Copy constructor vs Assignment Operator 


Which of the following two statements call copy constructor and which
one calls assignment operator? 

CPPMyClass t1, t2;

MyClass t3 = t1;  // ----> (1)

t2 = t1;          // -----> (2)

Copy constructor is called when a new object is created from an


existing object, as a copy of the existing object. Assignment operator is
called when an already initialized object is assigned a new value from
another existing object.
 In the following String class, we must write copy constructor. 

#include<iostream>

#include<cstring>

using namespace std;

 class String

private:

    char *s;

    int size;

public:

    String(const char *str = NULL); // constructor

    ~String() { delete [] s;  }// destructor

    String(const String&); // copy constructor

    void print() { cout << s << endl; } // Function


to print string

    void change(const char *);  // Function to change

};

 
String::String(const char *str)

    size = strlen(str);

    s = new char[size+1];

    strcpy(s, str);

void String::change(const char *str)

    delete [] s;

    size = strlen(str);

    s = new char[size+1];

    strcpy(s, str);

String::String(const String& old_str)

    size = old_str.size;

    s = new char[size+1];

    strcpy(s, old_str.s);
}

int main()

    String str1("GeeksQuiz");

    String str2 = str1;

    str1.print(); // what is printed ?

    str2.print();

    str2.change("GeeksforGeeks");

    str1.print(); // what is printed now ?

    str2.print();

    return 0;

Output: 
GeeksQuiz
GeeksQuiz
GeeksQuiz
GeeksforGeeks
What would be the problem if we remove copy constructor from
above code? 
If we remove copy constructor from the above program, we don’t get
the expected output. The changes made to str2 reflect in str1 as well
which is never expected. 
 

#include<iostream>

#include<cstring>

using namespace std;

class String

private:

    char *s;

    int size;

public:

    String(const char *str = NULL); // constructor

    ~String() { delete [] s;  }// destructor

    void print() { cout << s << endl; }

    void change(const char *);  // Function to change

};

String::String(const char *str)


{

    size = strlen(str);

    s = new char[size+1];

    strcpy(s, str);

void String::change(const char *str)

    delete [] s;

    size = strlen(str);

    s = new char[size+1];

    strcpy(s, str);

int main()

    String str1("GeeksQuiz");

    String str2 = str1;

    str1.print(); // what is printed ?


    str2.print();

    str2.change("GeeksforGeeks");

    str1.print(); // what is printed now ?

    str2.print();

    return 0;

Output: 
GeeksQuiz
GeeksQuiz
GeeksforGeeks
GeeksforGeeks

Assign values to Variables


introduced many new ways to declare a variable. Earlier assignment
and declaration was done using “=”
Example:
int a = 5;
But now 2 more ways are introduced in . They are:

Constructor initialization: In this way, the value of the variable is


enclosed in parentheses ( () ). In this way, value can be passed in
two ways shown below.

#include <iostream>
using namespace std;

  

// Driver Code

int main()

  

    // Declaring the variable in parentheses

    // Method 1

    int a(5);

    cout << "a = " << a;

  

    // Declaring the variable in parentheses

    // Method 2

    int b = (10);

    cout << endl

         << "b = " << b;

  

    return 0;

Output:
a = 5
b = 10
Explanation
In C++ 17, the variable can be declared by providing values through
parenthesis too. The difference between constructor initialization and
the old normal way of initialization is that it will always return last value
in the parenthesis no matter what it’s magnitude or sign is.

For example,
a=(2, 21, -50, 1)
he value stored in a would be 1.

Uniform initialization: In this way, the value of the variable is enclosed


in curly braces ( {} ) instead of parentheses. In this way, the value can
be passed in two ways shown below.

#include <iostream>

using namespace std;

  

int main()

  

    // Declaring the variable in curly braces

    // Method 1

    int a{ 3 };

    cout << "a = " << a;


  

    // Declaring the variable in curly braces

    // Method 2

    int b = { 7 };

    cout << endl

         << "b = " << b;

  

    return 0;

Output:
a = 3
b = 7

Constant and Static Class Members

we will be analyzing “static const”, “#define” and “enum”. These


three are often confusing and choosing which one to use can
sometimes be a difficult task.
static const
static const : “static const” is basically a combination of static(a
storage specifier) and const(a type qualifier).

Static : determines the lifetime and visibility/accessibility of the


variable. This means if a variable is declared as a static variable, it will
remain in the memory the whole time when the program is running,
while the normal or auto variables are destroyed when the function
(where the variable was defined) is over.

Const : is a type qualifier. A type qualifier is used to express additional


info about a value through type system. When a variable is initialized
using the const type qualifier, it will not accept further change in its
value.

So combining static and const, we can say that when a variable is


initialized using static const, it will retain its value till the execution
of the program and also, it will not accept any change in its value.
Syntax:

static const data_type name_of_variable = initial_value

#include <bits/stdc++.h>

  

using namespace std;

// function to add constant value to input

int addConst(int input)

    // value = 5 will be stored in

    // memory even after the

    // execution of the

    // function is finished

    static const int value = 5;

  

    // constant_not_static will


    // not accept change in value

    // but it will get destroyed

    // after the execution of

    // function is complete

    const int constant_not_static = 13;

    input += value;

  

    // value++; ==> this statement will produce


error

    return input;

  

int main()

    int input = 10;

    cout << addConst(input) << endl;

  

    return 0;

Output:
15
“What is #define“?
It is often misinterpreted as a programming statement. But it is actually
sets up a macro. A macro causes a text to replace before compilation
takes place. To know more about macros refer
to macros_vs_function article.
Syntax:
#define token [value]
NOTE: token should not have any spaces, value can have spaces.
Example:
#define ll long long int

// C++ program to demonstrate

// the use of #define

  

#include <bits/stdc++.h>

  

// defining long long int as => ll

#define ll long long int

  

// defining for loop

#define f(i, a, b, c) for (ll i = a; i < b; i += c)

using namespace std;

  

// function to count to a given number

void count(ll input)

{
    // loop implemented using macros

    // for(long long int j=1; j<input+1;j+=1)

    f(j, 1, input + 1, 1)

    {

        cout << j << " ";

    }

    cout << endl;

  

int main()

    // ll will get replaced by

    // long long int

    ll num = 10;

    count(num);

  

    return 0;

Output:
1 2 3 4 5 6 7 8 9 10

C++ Storage Management


C++ allows us to allocate the memory of a variable or an array in run

time. This is known as dynamic memory allocation.

In other programming languages such as Java and Python, the compiler


automatically manages the memories allocated to variables. But this is not
the case in C++.

In C++, we need to deallocate the dynamically allocated memory manually


after we have no use for the variable.

We can allocate and then deallocate memory dynamically using


the  new  and  delete  operators respectively.
C++ new Operator
The  new  operator allocates memory to a variable. For example,

// declare an int pointer


int* pointVar;

// dynamically allocate memory


// using the new keyword
pointVar = new int;

// assign value to allocated memory


*pointVar = 45;

delete Operator
Once we no longer need to use a variable that we have declared
dynamically, we can deallocate the memory occupied by the variable.

For this, the  delete  operator is used. It returns the memory to the operating
system. This is known as memory deallocation.
The syntax for this operator is
delete pointerVariable;

Consider the code:

// declare an int pointer


int* pointVar;

// dynamically allocate memory


// for an int variable
pointVar = new int;

// assign value to the variable memory


*pointVar = 45;

// print the value stored in memory


cout << *pointVar; // Output: 45

// deallocate the memory


delete pointVar;

1. C++ Dynamic Memory Allocation

#include <iostream>
using namespace std;

int main() {
// declare an int pointer
int* pointInt;

// declare a float pointer


float* pointFloat;

// dynamically allocate memory


pointInt = new int;
pointFloat = new float;

// assigning value to the memory


*pointInt = 45;
*pointFloat = 45.45f;
cout << *pointInt << endl;
cout << *pointFloat << endl;

// deallocate the memory


delete pointInt;
  delete pointFloat;

return 0;
}

Output

45
45.45

2: C++ new and delete Operator for Arrays

// C++ Program to store GPA of n number of students and display it


// where n is the number of students entered by the user

#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;

// memory allocation of num number of floats


ptr = new float[num];

cout << "Enter GPA of students." << endl;


for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}

cout << "\nDisplaying GPA of students." << endl;


for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << " :" << *(ptr + i) << endl;
}

// ptr memory is released


delete[] ptr;

return 0;
}

Output

Enter total number of students: 4


Enter GPA of students.
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9

Displaying GPA of students.


Student1 :3.6
Student2 :3.1
Student3 :3.9
Student4 :2.9

3.C++ new and delete Operator for Objects

#include <iostream>
using namespace std;

class Student {
int age;

public:

// constructor initializes age to 12


Student() : age(12) {}

void getAge() {
cout << "Age = " << age << endl;
}
};

int main() {
// dynamically declare Student object
Student* ptr = new Student();

// call getAge() function


ptr->getAge();

// ptr memory is released


delete ptr;

return 0;
}

Output

Age = 12

Input and Output in C ++ Programs


C++ comes with libraries that provide us with many ways for performing
input and output. In C++ input and output are performed in the form of a
sequence of bytes or more commonly known as streams.
 Input Stream: If the direction of flow of bytes is from the
device(for example, Keyboard) to the main memory then this
process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e.
from main memory to device( display screen ) then this
process is called output.
Header files available in C++ for Input/Output operations are: 
1. iostream: iostream stands for standard input-output stream.
This header file contains definitions to objects like cin, cout,
cerr etc.
2. iomanip: iomanip stands for input output manipulators. The
methods declared in this files are used for manipulating
streams. This file contains definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This
header file is used to handle the data being read from a file as
input or data being written into the file as output.
The two keywords cout in C++ and cin in C++ are used very often for
printing outputs and taking inputs respectively. These two are the most
basic methods of taking input and printing output in C++. To use cin
and cout in C++ one must include the header file iostream in the
program.
This article mainly discusses the objects defined in the header
file iostream like the cin and cout.  

Standard output stream (cout): Usually the standard output device is


the display screen. The C++ cout statement is the instance of the
ostream class. It is used to produce output on the standard output
device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout)
using the insertion operator(<<).

#include <iostream>

using namespace std;

int main()

    char sample[] = "GeeksforGeeks";

    cout << sample << " - A computer science portal


for geeks";

    return 0;

Output: 
GeeksforGeeks - A computer science portal for geeks
In the above program the insertion operator(<<) inserts the value of the
string variable sample followed by the string “A computer science
portal for geeks” in the standard output stream cout which is then
displayed on screen.
standard input stream (cin): Usually the input device in a computer
is the keyboard. C++ cin statement is the instance of the
class iostream and is used to read input from the standard input
device which is usually a keyboard. 
The extraction operator(>>) is used along with the object cin for
reading inputs. The extraction operator extracts the data from the
object cin which is entered using the keyboard.

#include <iostream>

using namespace std;

 int main()
{

    int age;

     cout << "Enter your age:";

    cin >> age;

    cout << "\nYour age is: " << age;

     return 0;

Output: 
Enter your age:
Your age is: 18
The above program asks the user to input the age. The object cin is
connected to the input device. The age entered by the user is extracted
from cin using the extraction operator(>>) and the extracted data is
then stored in the variable age present on the right side of the
extraction operator.
Un-buffered standard error stream (cerr): The C++ cerr is the
standard error stream which is used to output the errors. This is also an
instance of the iostream class. As cerr in C++ is un-buffered so it is
used when one needs to display the error message immediately. It
does not have any buffer to store the error message and display later.

#include <iostream>

using namespace std;

 int main()

    cerr << "An error occured";


    return 0;

Output: 
An error occurred
buffered standard error stream (clog): This is also an instance of
iostream class and used to display errors but unlike cerr the error is first
inserted into a buffer and is stored in the buffer until it is not fully filled.
or the buffer is not explicitly flushed (using flush()). The error message
will be displayed on the screen too.

#include <iostream>

 using namespace std;

 int main()

    clog << "An error occured";

    return 0;

Output: 
An error occured

Manipulators in C++ 
Manipulators are helping functions that can modify
the input/output stream. It does not mean that we change the value of a
variable, it only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.

For example, if we want to print the hexadecimal value of 100 then we


can print it as:
cout<<setbase(16)<<100

Types of Manipulators
There are various types of manipulators:
Manipulators without arguments: The most important manipulators
defined by the IOStream library are provided below.
 endl: It is defined in ostream. It is used to enter a new line
and after entering a new line it flushes (i.e. it forces all the output
written on the screen or in the file) the output stream.
 ws: It is defined in istream and is used to ignore the
whitespaces in the string sequence.
 ends: It is also defined in ostream and it inserts a null
character into the output stream. It typically works with
std::ostrstream, when the associated output buffer needs to be null-
terminated to be processed as a C string.
 flush: It is also defined in ostream and it flushes the output
stream, i.e. it forces all the output written on the screen or in the file.
Without flush, the output would be the same, but may not appear in
real-time.
Examples:

#include <iostream>

#include <istream>

#include <sstream>

#include <string>

  

using namespace std;

  

int main()

{
    istringstream str("           Programmer");

    string line;

    // Ignore all the whitespace in string

    // str before the first word.

    getline(str >> std::ws, line);

  

    // you can also write str>>ws

    // After printing the output it will


automatically

    // write a new line in the output stream.

    cout << line << endl;

  

    // without flush, the output will be the


same.

    cout << "only a test" << flush;

  

    // Use of ends Manipulator

    cout << "\na";

  

    // NULL character will be added in the


Output

    cout << "b" << ends;


    cout << "c" << endl;

  

    return 0;

Output:
Programmer
only a test
abc
Manipulators with Arguments: Some of the manipulators are used
with the argument like setw (20), setfill (‘*’), and many more. These all
are defined in the header file. If we want to use these manipulators then
we must include this header file in our program.

For Example, you can use following manipulators to set minimum width
and fill the empty space with any character you want: std::cout <<
std::setw (6) << std::setfill (’*’);
Some important manipulators in <iomanip> are:
 setw (val): It is used to set the field width in output
operations.
 setfill (c): It is used to fill the character ‘c’ on output stream.
 setprecision (val): It sets val as the new value for the
precision of floating-point values.
 setbase(val): It is used to set the numeric base value for
numeric values.
 setiosflags(flag): It is used to set the format flags specified
by parameter mask.
 resetiosflags(m): It is used to reset the format flags
specified by parameter mask.
Some important manipulators in <ios> are:
 showpos: It forces to show a positive sign on positive
numbers.
 noshowpos: It forces not to write a positive sign on positive
numbers.
 showbase: It indicates the numeric base of numeric values.
 uppercase: It forces uppercase letters for numeric values.
 nouppercase: It forces lowercase letters for numeric
values.
 fixed: It uses decimal notation for floating-point values.
 scientific: It uses scientific floating-point notation.
 hex: Read and write hexadecimal values for integers and it
works same as the setbase(16).
 dec: Read and write decimal values for integers i.e.
setbase(10).
 oct: Read and write octal values for integers i.e.
setbase(10).
 left: It adjusts output to the left.
 right: It adjusts output to the right.
Example:

#include <iomanip>

#include <iostream>

using namespace std;

  

int main()

    double A = 100;

    double B = 2001.5251;

    double C = 201455.2646;

  

    // We can use setbase(16) here instead of hex

  

    // formatting
    cout << hex << left << showbase <<
nouppercase;

  

    // actual printed part

    cout << (long long)A << endl;

  

    // We can use dec here instead of setbase(10)

  

    // formatting

    cout << setbase(10) << right << setw(15)

         << setfill('_') << showpos

         << fixed << setprecision(2);

  

    // actual printed part

    cout << B << endl;

  

    // formatting

    cout << scientific << uppercase

         << noshowpos << setprecision(9);

  

    // actual printed part


    cout << C << endl;

Output:
0x64
_______+2001.53
2.014552646E+05

Unformatted input/output operations In


C++
 we will discuss the unformatted Input/Output operations In C++.
Using objects cin and cout for the input and the output of data of
various types is possible because of overloading of
operator >> and << to recognize all the basic C++ types. The
operator >> is overloaded in the istream class and operator << is
overloaded in the ostream class.
The general format for reading data from the keyboard:
cin >> var1 >> var2 >> …. >> var_n;
 Here, var1, var2, ……, varn are the variable names that are
declared already.
 The input data must be separated by white space characters
and the data type of user input must be similar to the data
types of the variables which are declared in the program.
 The operator >> reads the data character by character and
assigns it to the indicated location.

// C++ program to illustrate the

// input and output of the data

// enterred by user

#include <iostream>
using namespace std;

  

// Driver Code

int main()

    int data;

    char val;

  

    // Input the data

    cin >> data;

    cin >> val;

  

    // Print the data

    cout << data << "   " << val;

  

    return 0;

Output:
Explanation: In the above program, 123 is stored in the variable val of
integer, and B is passed to the next cin object and stored in the data
variable of character.

put() and get() functions:


The class istream and ostream have predefined
functions get() and put(), to handle single character input and output
operations. The function get() can be used in two ways, such
as get(char*) and get(void) to fetch characters including blank spaces,
newline characters, and tab. The function get(char*) assigns the value
to a variable and get(void) to return the value of the character.
Syntax:
char data;
// get() return the character value and assign to data variable
data = cin.get();
// Display the value stored in data variable
cout.put(data); 

// C++ program to illustrate the

// input and output of data using

// get() and puts()

#include <iostream>

using namespace std;

  

// Driver Code

int main()

    char data;

    int count = 0;
  

    cout << "Enter Data: ";

  

    // Get the data

    cin.get(data);

  

    while (data != '\n') {

        // Print the data

        cout.put(data);

        count++;

  

        // Get the data again

        cin.get(data);

    }

  

    return 0;

Output:

getline() and write() functions :


In C++, the function getline() and write() provide a more efficient way to
handle line-oriented inputs and outputs. getline() function reads the
complete line of text that ends with the new line character. This function
can be invoked using the cin object.
Syntax:

cin.getline(variable_to_store_line, size);

The reading is terminated by the ‘\n’ character. The new character is


read by the function, but it does not display it, instead, it is replaced
with a NULL character.

// C++ program to illustrate the

// input and output of file using

// getline() and write() function

#include <iostream>

#include <string>

using namespace std;

  

// Driver Code

int main()

    char line[100];

  

    // Get the input

    cin.getline(line, 10);

  

    // Print the data


    cout.write(line, 5);

    cout << endl;

  

    // Print the data

    cout.write(line, 20);

  

    cout << endl;

  

    return 0;

Output:

File Handling through C++ Classes


In C++, files are mainly dealt by using three classes fstream, ifstream,
ofstream available in fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Now the first step to open the particular file for read or write operation.
We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
For e.g.
Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode =
ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);
Open File by using open method
Calling of default constructor
ifstream fin;
fin.open(filename, openmode)
fin.open(“filename”);

Default Open Modes :


ifstream ios::in

ofstream ios::out

fstream ios::in | ios::out

Problem Statement : To read and write a File in C++.


Examples:
Input :
Welcome in bit. Best way to learn things.
-1
Output :
Welcome in bit. Best way to learn things.
Below is the implementation by using ifsream & ofstream classes.
C++

/* File Handling with C++ using ifstream & ofstream class


object*/

/* To write the Content in File*/

/* Then to read the content of file*/

#include <iostream>

  

/* fstream header file for ifstream, ofstream, 

  fstream classes */

#include <fstream>

  

using namespace std;

  

// Driver Code

int main()

    // Creation of ofstream class object

    ofstream fout;

  

    string line;
  

    // by default ios::out mode, automatically deletes

    // the content of file. To append the content, open in


ios:app

    // fout.open("sample.txt", ios::app)

    fout.open("sample.txt");

  

    // Execute a loop If file successfully opened

    while (fout) {

  

        // Read a Line from standard input

        getline(cin, line);

  

        // Press -1 to exit

        if (line == "-1")

            break;

  

        // Write line in file

        fout << line << endl;

    }

  
    // Close the File

    fout.close();

  

    // Creation of ifstream class object to read the file

    ifstream fin;

  

    // by default open mode = ios::in mode

    fin.open("sample.txt");

  

    // Execute a loop until EOF (End of File)

    while (fin) {

  

        // Read a Line from File

        getline(fin, line);

  

        // Print line in Console

        cout << line << endl;

    }

  

    // Close the file

    fin.close();
  

    return 0;

Below is the implementation by using fstream class.


C++

/* File Handling with C++ using fstream class object */

/* To write the Content in File */

/* Then to read the content of file*/

#include <iostream>

  

/* fstream header file for ifstream, ofstream, 

   fstream classes */

#include <fstream>

  

using namespace std;

  

// Driver Code

int main()

    // Creation of fstream class object

    fstream fio;
  

    string line;

  

    // by default openmode = ios::in|ios::out mode

    // Automatically overwrites the content of file, To


append

    // the content, open in ios:app

    // fio.open("sample.txt", ios::in|ios::out|ios::app)

    // ios::trunc mode delete all conetent before open

    fio.open("sample.txt", ios::trunc | ios::out | ios::in);

  

    // Execute a loop If file successfully Opened

    while (fio) {

  

        // Read a Line from standard input

        getline(cin, line);

  

        // Press -1 to exit

        if (line == "-1")

            break;

  
        // Write line in file

        fio << line << endl;

    }

  

    // Execute a loop untill EOF (End of File)

    // point read pointer at beginning of file

    fio.seekg(0, ios::beg);

  

    while (fio) {

  

        // Read a Line from File

        getline(fio, line);

  

        // Print line in Console

        cout << line << endl;

    }

  

    // Close the file

    fio.close();

  

    return 0;
}

Read/Write Class Objects from/to File


in C++
Given a file “Input.txt” in which every line has values same as instance
variables of a class. 
Read the values into the class’s object and do necessary operations.

Examples: 
Input :
Input.txt :
Michael 19 1806
Kemp 24 2114
Terry 21 2400
Operation : Print the name of the highest
rated programmer.

Output :
Terry

// C++ program to demonstrate read/write of class

// objects in C++.

#include <iostream>

#include <fstream>

using namespace std;

// Class to define the properties

class Contestant {

public:
    // Instance variables

    string Name;

    int Age, Ratings;

    // Function declaration of input() to input info

    int input();

    // Function declaration of


output_highest_rated() to

    // extract info from file Data Base

    int output_highest_rated();

};

// Function definition of input() to input info

int Contestant::input()

    // Object to write in file

    ofstream file_obj;

    // Opening file in append mode

    file_obj.open("Input.txt", ios::app);
 

    // Object of class contestant to input data in


file

    Contestant obj;

    // Feeding appropriate data in variables

    string str = "Michael";

    int age = 18, ratings = 2500;

    // Assigning data into object

    obj.Name = str;

    obj.Age = age;

    obj.Ratings = ratings;

    // Writing the object's data in file

    file_obj.write((char*)&obj, sizeof(obj));

    // Feeding appropriate data in variables

    str = "Terry";

    age = 21;

    ratings = 3200;
 

    // Assigning data into object

    obj.Name = str;

    obj.Age = age;

    obj.Ratings = ratings;

    // Writing the object's data in file

    file_obj.write((char*)&obj, sizeof(obj));

    return 0;

// Function definition of output_highest_rated() to

// extract info from file Data Base

int Contestant::output_highest_rated()

    // Object to read from file

    ifstream file_obj;

    // Opening file in input mode


    file_obj.open("Input.txt", ios::in);

    // Object of class contestant to input data in


file

    Contestant obj;

    // Reading from file into object "obj"

    file_obj.read((char*)&obj, sizeof(obj));

    // max to store maximum ratings

    int max = 0;

    // Highest_rated stores the name of highest


rated contestant

    string Highest_rated;

    // Checking till we have the feed

    while (!file_obj.eof()) {

        // Assigning max ratings

        if (obj.Ratings > max) {

            max = obj.Ratings;
            Highest_rated = obj.Name;

        }

        // Checking further

        file_obj.read((char*)&obj, sizeof(obj));

    }

    // Output is the highest rated contestant

    cout << Highest_rated;

    return 0;

// Driver code

int main()

    // Creating object of the class

    Contestant object;

    // Inputting the data

    object.input();
 

    // Extracting the max rated contestant

    object.output_highest_rated();

    return 0;

Output: 
Terry

C++ Exception Handling


An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
 throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
 catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.
 try − A try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the
code that might generate an exception. Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.

Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can be
any expression and the type of the result of the expression determines the type of
exception thrown.
Following is an example of throwing an exception when dividing by zero condition
occurs −
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type.
try {
// protected code
} catch(...) {
// code to handle any exception
}

The following is an example, which throws a division by zero exception and we catch
it in catch block.

#include <iostream>
using namespace std;

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

int main () {
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}

Because we are raising an exception of type const char*, so while catching this


exception, we have to use const char* in catch block. If we compile and run above
code, this would produce the following result −
Division by zero condition!

C++ Standard Exceptions


C++ provides a list of standard exceptions defined in <exception> which we can
use in our programs. These are arranged in a parent-child class hierarchy shown
below −
Here is the small description of each exception mentioned in the above hierarchy −

Sr.No Exception & Description

1 std::exception
An exception and parent class of all the standard C++ exceptions.

2
std::bad_alloc
This can be thrown by new.

3 std::bad_cast
This can be thrown by dynamic_cast.

4 std::bad_exception
This is useful device to handle unexpected exceptions in a C++
program.
5 std::bad_typeid
This can be thrown by typeid.

6 std::logic_error
An exception that theoretically can be detected by reading the
code.

7 std::domain_error
This is an exception thrown when a mathematically invalid domain
is used.

8 std::invalid_argument
This is thrown due to invalid arguments.

9 std::length_error
This is thrown when a too big std::string is created.

10 std::out_of_range
This can be thrown by the 'at' method, for example a std::vector
and std::bitset<>::operator[]().

11 std::runtime_error
An exception that theoretically cannot be detected by reading the
code.

12 std::overflow_error
This is thrown if a mathematical overflow occurs.

13 std::range_error
This is occurred when you try to store a value which is out of range.

14 std::underflow_error
This is thrown if a mathematical underflow occurs.
Define New Exceptions
You can define your own exceptions by inheriting and overriding exception class
functionality. Following is the example, which shows how you can use
std::exception class to implement your own exception in standard way

#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception {


const char * what () const throw () {
return "C++ Exception";
}
};

int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}

This would produce the following result −


MyException caught
C++ Exception

Catching base and derived classes as


exceptions
Exception Handling – catching base and derived classes as exceptions:
If both base and derived classes are caught as exceptions then catch block of
derived class must appear before the base class.
If we put base class first then the derived class catch block will never be
reached. For example, following C++ code prints “Caught Base Exception”

#include<iostream>

using namespace std;


  

class Base {};

class Derived: public Base {};

int main()

   Derived d;

   // some other stuff

   try {

       // Some monitored code

       throw d;

   }

   catch(Base b) { 

        cout<<"Caught Base Exception";

   }

   catch(Derived d) {  //This catch block is NEVER


executed

        cout<<"Caught Derived Exception";

   }

   getchar();

   return 0;

}
In the above C++ code, if we change the order of catch statements then
both catch statements become reachable. Following is the modifed
program and it prints “Caught Derived Exception”

#include<iostream>

using namespace std;

  

class Base {};

class Derived: public Base {};

int main()

   Derived d;

   // some other stuff

   try {

       // Some monitored code

       throw d;

   }

   catch(Derived d) { 

        cout<<"Caught Derived Exception";

   }

   catch(Base b) { 

        cout<<"Caught Base Exception";

   }
   getchar();

   return 0;

Exception Hirarchies
Predict the output of following C++ program.

#include <iostream>

using namespace std;

  

class Test {

public:

  Test() { cout << "Constructing an object of Test "


<< endl; }

  ~Test() { cout << "Destructing an object of Test


"  << endl; }

};

  

int main() {

  try {

    Test t1;
    throw 10;

  } catch(int i) {

    cout << "Caught " << i << endl;

  }

Output:
Constructing an object of Test
Destructing an object of Test
Caught 10
When an exception is thrown, destructors of the objects (whose scope
ends with the try block) is automatically called before the catch block
gets exectuted.

Consider the following program.

#include <iostream>

using namespace std;

  

class Test1 {

public:

  Test1() { cout << "Constructing an Object of


Test1" << endl; }

  ~Test1() { cout << "Destructing an Object of


Test1" << endl; }

};
  

class Test2 {

public:

  // Following constructor throws an integer


exception

  Test2() { cout << "Constructing an Object of


Test2" << endl; 

            throw 20; }

  ~Test2() { cout << "Destructing an Object of


Test2" << endl; }

};

  

int main() {

  try {

    Test1 t1;  // Constructed and destructed

    Test2 t2;  // Partially constructed

    Test1 t3;  // t3 is not constructed as this


statement never gets executed

  } catch(int i) {

    cout << "Caught " << i << endl;

  }

Output:
Constructing an Object of Test1
Constructing an Object of Test2
Destructing an Object of Test1
Caught 20

Inside and Exception Handler

Destructors are only called for the completely constructed objects.


When constructor of an object throws an exception, destructor for that
object is not called.
As an excecise, predict the output of following program.

#include <iostream>

using namespace std;

  

class Test {

  static int count;

  int id;

public:

  Test() {

    count++;

    id = count;

    cout << "Constructing object number " << id <<


endl;

    if(id == 4)

       throw 4;

  }

  ~Test() { cout << "Destructing object number " <<


id << endl; }

};

  

int Test::count = 0;

  

int main() {

  try {

    Test array[5];

  } catch(int i) {

    cout << "Caught " << i << endl;

  }

}
Templates in C++
A template is a simple and yet very powerful tool in C++. The simple
idea is to pass data type as a parameter so that we don’t need to write
the same code for different data types

C++ adds two new keywords to support


templates: ‘template’  and ‘typename’. The second keyword can always
be replaced by keyword ‘class’.

How do templates work? 


Templates are expanded at compiler time. This is like macros. The
difference is, the compiler does type checking before template
expansion. The idea is simple, source code contains only
function/class, but compiled code may contain multiple copies of same
function/class. 
 

 
Function Templates We write a generic function that can be used for
different data types. Examples of function templates are sort(), max(),
min(), printArray(). 
#include <iostream>

using namespace std;

// One function works for all data types.  This


would work

// even for user defined types if operator '>' is


overloaded

template <typename T>

T myMax(T x, T y)

   return (x > y)? x: y;

int main()

  cout << myMax<int>(3, 7) << endl;  // Call myMax


for int

  cout << myMax<double>(3.0, 7.0) << endl; // call


myMax for double

  cout << myMax<char>('g', 'e') << endl;   // call


myMax for char

  return 0;
}

Output: 
7
7
g

Below is the program to implement Bubble Sort using templates in C+


+: 

// CPP code for bubble sort

// using template function

#include <iostream>

using namespace std;

  

// A template function to implement bubble sort.

// We can use this for any data type that supports

// comparison operator < and swap works for it.

template <class T>

void bubbleSort(T a[], int n) {

    for (int i = 0; i < n - 1; i++)

        for (int j = n - 1; i < j; j--)

            if (a[j] < a[j - 1])


              swap(a[j], a[j - 1]);

  

// Driver Code

int main() {

    int a[5] = {10, 50, 30, 40, 20};

    int n = sizeof(a) / sizeof(a[0]);

  

    // calls template function

    bubbleSort<int>(a, n);

  

    cout << " Sorted array : ";

    for (int i = 0; i < n; i++)

        cout << a[i] << " ";

    cout << endl;

  

  return 0;

Output: 
 
Sorted array : 10 20 30 40 50
Class Templates Like function templates, class templates are useful
when a class defines something that is independent of the data type.

#include <iostream>

using namespace std;

template <typename T>

class Array {

private:

    T *ptr;

    int size;

public:

    Array(T arr[], int s);

    void print();

};

template <typename T>

Array<T>::Array(T arr[], int s) {

    ptr = new T[s];

    size = s;

    for(int i = 0; i < size; i++)


        ptr[i] = arr[i];

template <typename T>

void Array<T>::print() {

    for (int i = 0; i < size; i++)

        cout<<" "<<*(ptr + i);

    cout<<endl;

int main() {

    int arr[5] = {1, 2, 3, 4, 5};

    Array<int> a(arr, 5);

    a.print();

    return 0;

Output: 
1 2 3 4 5

Can there be more than one arguments to templates? 


Yes, like normal parameters, we can pass more than one data types as
arguments to templates. The following example demonstrates the
same. 
 

#include<iostream>

using namespace std;

template<class T, class U>

class A  {

    T x;

    U y;

public:

    A() {    cout<<"Constructor Called"<<endl;   }

};

int main()  {

   A<char, char> a;

   A<int, double> b;

   return 0;

Output: 
Constructor Called
Constructor Called
Can we specify default value for template arguments? 
Yes, like normal parameters, we can specify default arguments to
templates. The following example demonstrates the same. 
 

#include<iostream>

using namespace std;

template<class T, class U = char>

class A  {

public:

    T x;

    U y;

    A() {   cout<<"Constructor Called"<<endl;   }

};

int main()  {

   A<char> a;  // This will call A<char, char>  

   return 0;

Output: 
Constructor Called
What is the difference between function overloading and
templates? 
Both function overloading and templates are examples of polymorphism
feature of OOP. Function overloading is used when multiple functions
do similar operations, templates are used when multiple functions do
identical operations.
C++ Standard Template Library (STL)

The Standard Template Library (STL) is a set of C++ template classes


to provide common programming data structures and functions such as
lists, stacks, arrays, etc. It is a library of container classes, algorithms,
and iterators. It is a generalized library and so, its components are
parameterized. A working knowledge of template classes is a
prerequisite for working with STL.
STL has four components
 Algorithms
 Containers
 Functions
 Iterators
Algorithms
The header algorithm defines a collection of functions especially
designed to be used on ranges of elements.They act on containers and
provide means for various operations for the contents of the containers.
 Algorithm
 Sorting
 Searching
 Important STL Algorithms
 Useful Array algorithms
 Partition Operations
 Numeric
 valarray class
Containers

Containers or container classes store objects and data. There are in


total seven standard “first-class” container classes and three container
adaptor classes and only seven header files that provide access to
these containers or container adaptors.
 Sequence Containers: implement data structures which can be
accessed in a sequential manner.
 vector
 list
 deque
 arrays
 forward_list( Introduced in C++11)
 Container Adaptors : provide a different interface for sequential
containers.
 queue
 priority_queue
 stack
 Associative Containers : implement sorted data structures that
can be quickly searched (O(log n) complexity).
 set
 multiset
 map
 multimap
 Unordered Associative Containers : implement unordered data
structures that can be quickly searched
 unordered_set (Introduced in C++11)
 unordered_multiset (Introduced in C++11)
 unordered_map (Introduced in C++11)
 unordered_multimap (Introduced in C++11)

Flowchart of Adaptive Containers and Unordered Containers


Flowchart of Sequence conatiners and ordered containers

Functions
The STL includes classes that overload the function call operator.
Instances of such classes are called function objects or functors.
Functors allow the working of the associated function to be customized
with the help of parameters to be passed.
 Functors
Iterators
As the name suggests, iterators are used for working upon a sequence
of values. They are the major feature that allow generality in STL.
 Iterators
Utility Library
Defined in header <utility>.
 pair

Sequence containers
Sequence containers implement data structures which can be
accessed sequentially.
 array: Static contiguous array (class template)
 vector: Dynamic contiguous array (class template)
 deque: Double-ended queue (class template)
 forward_list: Singly-linked list (class template)
 list : Doubly-linked list (class template)
Associative containers
Associative containers implement sorted data structures that can be
quickly searched (O(log n) complexity).
 Set: Collection of unique keys, sorted by keys
(class template)
 Map: Collection of key-value pairs, sorted by keys, keys are
unique (class template).
 multiset: Collection of keys, sorted by keys (class template)
 multimap: Collection of key-value pairs, sorted by keys
(class template)
Unordered associative containers
Unordered associative containers implement unsorted (hashed) data
structures that can be quickly searched (O(1) amortized, O(n) worst-
case complexity).
 unordered_set: Collection of unique keys, hashed by keys.
(class template)
 unordered_map: Collection of key-value pairs, hashed by
keys, keys are unique. (class template)
 unordered_multiset:  Collection of keys, hashed by keys
(class template)
 unordered_multimap:  Collection of key-value pairs, hashed
by keys (class template)
Container adaptors
Container adaptors provide a different interface for sequential
containers.
 stack: Adapts a container to provide stack (LIFO data
structure) (class template).
 queue: Adapts a container to provide queue (FIFO data
structure) (class template).
 priority_queue: Adapts a container to provide priority queue
(class template).
Flowchart of Adaptive Containers and Unordered Containers

Flowchart of Sequence conatiners and ordered containers

You might also like