Professional Documents
Culture Documents
C++ Programming
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.
#include <iostream>
using namespace std;
C++ is a middle-level language, as it encapsulates both high- and low-level language features.
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a data
structure.
Usage of C++
By the help of C++ programming language, we can develop different types of secured and robust
applications:
o Window application
o Client-Server application
o Device drivers
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.
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.
#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...
#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
Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
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.
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.
#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;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
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.
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.
int main() {
char str[] = "Hello C++";
int main() {
char name[50];
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
int main() {
char str[] = "Unable to read....";
int main() {
char str[] = "Unable to read....";
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() {
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.
Coding standards
Coding standards are collections of rules and guidelines that determine the
programming style, procedures, and methods for a programming language.
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.
Without predefined conditions that all team member should follow can result
in the following:
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
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;
return 0;
}
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 −
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.
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;
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:
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;
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
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;
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;
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 −
int 0
char '\0'
float 0
double 0
pointer NULL
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:
#include <iostream>
if (x > y)
return x;
else
return y;
int main()
Output:
m is 20
Syntax:
DataType ArrayName[size_of_array];
Example:
#include <iostream>
int main()
// Array Derived Type
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3 / 2] = 2;
arr[3] = arr[0];
return 0;
Output:
2 -10 5
Example:
// C++ program to illustrate
#include <bits/stdc++.h>
void geeks()
int* ptr;
ptr = &var;
// to a pointer
cout << "Value at ptr = "
// Driver program
int main()
geeks();
Output:
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20
#include <iostream>
int main()
int x = 10;
int& ref = x;
ref = 20;
x = 30;
return 0;
Output:
x = 20
ref = 30
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
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).
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'
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.
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
};
#include <iostream>
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.
#include <iostream>
// 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);
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 −
A derived class inherits all base class methods with the following exceptions −
protected:
int width;
int height;
};
// 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();
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Total paint cost: $2450
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.
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;
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++
#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;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// 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
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;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
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
#include <iostream>
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
// 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
#include <bits/stdc++.h>
class Geeks
public:
int id;
//Default Constructor
Geeks()
{
id=-1;
}
//Parametrized Constructor
Geeks(int x)
{
id=x;
}
};
int main() {
Geeks obj1;
Geeks obj2(21);
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.
#include <bits/stdc++.h>
class Geeks
public:
int id;
~Geeks()
{
}
};
int main()
{
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
Geeks obj2;
obj2.id=i;
i++;
return 0;
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
class Person {
private:
int age;
public:
// 1. Constructor with no arguments
Person() {
age = 20;
}
int getAge() {
return age;
}
};
int main() {
Person person1, person2(45);
return 0;
}
Output
Person1 Age = 20
Person2 Age = 45
2: Constructor overloading
class Room {
private:
double length;
double breadth;
public:
// 1. Constructor with no arguments
Room() {
length = 6.9;
breadth = 4.2;
}
double calculateArea() {
return length * breadth;
}
};
int main() {
Room room1, room2(8.2, 6.6), room3(8.2);
cout << "\nWhen breadth is fixed to 7.2 and (8.2) is passed:" << endl;
cout << "Area of room = " << room3.calculateArea() << endl;
return 0;
}
Output
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>
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
Width of box : 10
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:
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.
#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>
class Point
{
private:
int x, y;
public:
};
int main()
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
#include<iostream>
#include<cstring>
class String
private:
char *s;
int size;
public:
};
String::String(const char *str)
size = strlen(str);
strcpy(s, str);
delete [] s;
size = strlen(str);
strcpy(s, str);
size = old_str.size;
strcpy(s, old_str.s);
}
int main()
String str1("GeeksQuiz");
str2.print();
str2.change("GeeksforGeeks");
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>
class String
private:
char *s;
int size;
public:
};
size = strlen(str);
strcpy(s, str);
delete [] s;
size = strlen(str);
strcpy(s, str);
int main()
String str1("GeeksQuiz");
str2.change("GeeksforGeeks");
str2.print();
return 0;
Output:
GeeksQuiz
GeeksQuiz
GeeksforGeeks
GeeksforGeeks
#include <iostream>
using namespace std;
// Driver Code
int main()
// Method 1
int a(5);
// Method 2
int b = (10);
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.
#include <iostream>
int main()
// Method 1
int a{ 3 };
// Method 2
int b = { 7 };
return 0;
Output:
a = 3
b = 7
#include <bits/stdc++.h>
input += value;
return input;
int main()
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
#include <bits/stdc++.h>
{
// loop implemented using macros
f(j, 1, input + 1, 1)
{
}
int main()
count(num);
return 0;
Output:
1 2 3 4 5 6 7 8 9 10
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;
#include <iostream>
using namespace std;
int main() {
// declare an int pointer
int* pointInt;
return 0;
}
Output
45
45.45
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;
return 0;
}
Output
#include <iostream>
using namespace std;
class Student {
int age;
public:
void getAge() {
cout << "Age = " << age << endl;
}
};
int main() {
// dynamically declare Student object
Student* ptr = new Student();
return 0;
}
Output
Age = 12
#include <iostream>
int main()
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>
int main()
{
int 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>
int main()
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>
int main()
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.
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>
int main()
{
istringstream str(" Programmer");
string line;
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>
int main()
double A = 100;
double B = 2001.5251;
double C = 201455.2646;
// formatting
cout << hex << left << showbase <<
nouppercase;
// formatting
// formatting
Output:
0x64
_______+2001.53
2.014552646E+05
// enterred by user
#include <iostream>
using namespace std;
// Driver Code
int main()
int data;
char 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.
#include <iostream>
// Driver Code
int main()
char data;
int count = 0;
cin.get(data);
cout.put(data);
count++;
cin.get(data);
}
return 0;
Output:
cin.getline(variable_to_store_line, size);
#include <iostream>
#include <string>
// Driver Code
int main()
char line[100];
cin.getline(line, 10);
cout.write(line, 20);
return 0;
Output:
ofstream ios::out
#include <iostream>
fstream classes */
#include <fstream>
// Driver Code
int main()
ofstream fout;
string line;
fout.open("sample.txt");
while (fout) {
getline(cin, line);
break;
}
// Close the File
fout.close();
ifstream fin;
fin.open("sample.txt");
while (fin) {
getline(fin, line);
}
fin.close();
return 0;
#include <iostream>
fstream classes */
#include <fstream>
// Driver Code
int main()
fstream fio;
string line;
while (fio) {
getline(cin, line);
break;
// Write line in file
}
fio.seekg(0, ios::beg);
while (fio) {
getline(fio, line);
}
fio.close();
return 0;
}
Examples:
Input :
Input.txt :
Michael 19 1806
Kemp 24 2114
Terry 21 2400
Operation : Print the name of the highest
rated programmer.
Output :
Terry
// objects in C++.
#include <iostream>
#include <fstream>
class Contestant {
public:
// Instance variables
string Name;
int input();
int output_highest_rated();
};
int Contestant::input()
ofstream file_obj;
file_obj.open("Input.txt", ios::app);
Contestant obj;
obj.Name = str;
obj.Age = age;
obj.Ratings = ratings;
file_obj.write((char*)&obj, sizeof(obj));
str = "Terry";
age = 21;
ratings = 3200;
obj.Name = str;
obj.Age = age;
obj.Ratings = ratings;
file_obj.write((char*)&obj, sizeof(obj));
return 0;
int Contestant::output_highest_rated()
ifstream file_obj;
Contestant obj;
file_obj.read((char*)&obj, sizeof(obj));
int max = 0;
string Highest_rated;
while (!file_obj.eof()) {
max = obj.Ratings;
Highest_rated = obj.Name;
}
file_obj.read((char*)&obj, sizeof(obj));
}
return 0;
// Driver code
int main()
Contestant object;
object.input();
object.output_highest_rated();
return 0;
Output:
Terry
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;
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;
}
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;
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
}
}
#include<iostream>
int main()
Derived d;
try {
throw d;
}
catch(Base b) {
}
}
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>
int main()
Derived d;
try {
throw d;
}
catch(Derived d) {
}
catch(Base b) {
}
getchar();
return 0;
Exception Hirarchies
Predict the output of following C++ program.
#include <iostream>
class Test {
public:
};
int main() {
try {
Test t1;
throw 10;
} catch(int i) {
}
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.
#include <iostream>
class Test1 {
public:
};
class Test2 {
public:
throw 20; }
};
int main() {
try {
} catch(int i) {
}
Output:
Constructing an Object of Test1
Constructing an Object of Test2
Destructing an Object of Test1
Caught 20
#include <iostream>
class Test {
int id;
public:
Test() {
count++;
id = count;
if(id == 4)
throw 4;
}
};
int Test::count = 0;
int main() {
try {
Test array[5];
} catch(int i) {
}
}
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
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>
T myMax(T x, T y)
int main()
return 0;
}
Output:
7
7
g
#include <iostream>
// Driver Code
int main() {
bubbleSort<int>(a, n);
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>
class Array {
private:
T *ptr;
int size;
public:
void print();
};
size = s;
void Array<T>::print() {
cout<<endl;
int main() {
a.print();
return 0;
Output:
1 2 3 4 5
#include<iostream>
class A {
T x;
U y;
public:
};
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>
class A {
public:
T x;
U y;
};
int main() {
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)
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