MDU BCA- Object Oriented Programing(C++)
MDU BCA- Object Oriented Programing(C++)
CONTACT NO-7827646303
2
SECTION-II
Abstracting Mechanism:
Classes
Private and Public
Constructor and Destructor
Member Function
Static Member
Refrences
Memory Management:
New
Delete
Object Copying
Copy Constuctor
Assignment Operator
This Input/Output
SECTION-III
Inheritance and Polymorphism:
Derived Class and Base Class
Different Types of Inheritance
Overriding Member Function
Abstract Class
Public and Private Inheritance
Ambiguity in Multiple Inheritance
Virtual Function
Friend Function
Static Function
4
SECTION-IV
Exception Handling:
Exception and Derived Class
Function Exception Declaration
Unexpected Exception
Exception When Handling Exception
Resource Capure and Release
Template and Standard Template Library:
Template Classes
Template Declaration
Template Function
Namespace
String
Iterators
Hashes
Iostreams and other types
5
SECTION-I
Object Oriented Programing Concept
Procedural Language and Object Oriented
Approach:
Procedural Programming
It is defined as a programming language derived from the structure programming and
based on calling procedures. The procedures are the functions, routines, or
subroutines that consist of the computational steps required to be carried. It follows a
step-by-step approach in order to break down a task into a set of variables and
routines via a sequence of instructions.
During the program's execution, a procedure can be called at any point, either by other
procedures or by itself. The examples of procedural programming are ALGOL, COBOL,
BASIC, PASCAL, FORTRAN, and C.
Object-oriented programming
Object-oriented programming is a computer programming design philosophy or
methodology that organizes/ models software design around data or objects rather
than functions and logic. It includes two words, "object" and "oriented". In a dictionary
object is an article or entity that exists in the real world. The meaning of oriented is
interested in a particular kind of thing or entity. In layman's terms, it is a programming
pattern that rounds around an object or entity.
OOP is said to be the most popular programming model among developers. It is well
suited for programs that are large, complex, and actively updated or maintained. It
makes the development and maintenance of software easy by providing major
concepts such as abstraction, inheritance, polymorphism, and encapsulation. These
four are also the four pillars of an object-oriented programming system.
OOPs, provide the ability to simulate real-world events much more effectively. We can
provide the solution to real-world problems if we are using the Object-Oriented
Programming language. OOPs, provide data hiding, whereas, in Procedure-oriented
programming language, global data can be accessed from anywhere.
The examples of OOPs are - C#, Python, C++, Java, PHP, Scala, Perl, etc.
Now, let's see the comparison between Procedural programming and object-oriented
programming. We are comparing both terms on the basis of some characteristics. The
difference between both languages are tabulated as follows -
7
13. Data hiding There is not any proper way for There is a possibility of
data hiding. data hiding.
Charactetics of OOPs:
The characteristics of object oriented programming are as follows:
1. Objects
9
Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program must handle.The fundamental idea behind object oriented approach is to
combine both data and function into a single unit and these units are called objects.
The term objects means a combination of data and program that represent some
real word entity.
When a program executed, the object interact by sending messages to one another.
Each object contain data, and code to manipulate the data.
2. Class
A group of objects that share common properties for data part and some program
part are collectively called as class. In C ++ a class is a new data type that contains
member variables and member functions that operate on the variables.
The entire set of data and code of an object can be made a user-defined data type
with the help of a class. Objects are variable of the type class. Once a class has
been defined, we can create any number of objects belonging to that class.
<classname><objectname>;
employee manager;
3. Encapsulation
4. Data Abstraction
Abstraction refers to the act of representing essential features without including the
back ground details or explanation. Classes use the concept of abstraction and are
defined as a list of attributes such as size, weight, cost and functions to operate on
these attributes. They encapsulate all essential properties of the object that are to be
created. The attributes are called as data members as they hold data and the
functions which operate on these data are called as member functions.
10
Class use the concept of data abstraction so they are called abstract data type
(ADT).
5. Inheritance
Inheritance is the mechanism by which one class can inherit the properties of
another. It allows a hierarchy of classes to be build, moving from the most general
to the most specific. When one class is inherited by another, the class that is
inherited is called the base class. The inheriting class is called the derived class. In
general, the process of inheritance begins with the definition of a base class. The
base class defines all qualities that will be common to any derived class. . In OOPs,
the concept of inheritance provides the idea of reusability. In essence, the base
class represent the most general description of a set of traits. The derived class
inherits those general traits and adds properties that are specific to that class.
6. Polymorphism
Polymorphism comes from the Greek words “poly” and “morphism”. “poly”
means many and “morphism” means form i.e.. many forms. Polymorphism means
the ability to take more than one form. For example, an operation have different
behavior in different instances. The behavior depends upon the type of the data
used in the operation.
1) Function overloading
2) Operator overloading
It is able to express the operation of addition by a single operater say ‘+’. When
this is possible you use the expression x + y to denote the sum of x and y, for many
different types of x and y; integers , float and complex no. You can even define the
+ operation for two strings to mean the concatenation of the strings.
7. Dynamic Binding
Binding refers to the linking of a procedure call to the code to the executed in
response to the call. Dynamic binding means the code associated with a given
procedure call is not known until the time of the call at run-time. It is associated
with a polymorphic reference depends upon the dynamic type of that reference.
11
8. Message Passing
An object oriented program consists of a set of objects that communicate with each
other.
A message for an object is a request for execution of a procedure and therefore will
invoke a function (procedure) in the receiving object that generates the desired
result. Message passing involves specifying the name of the object, the name of the
function (message) and information to be sent.
User-Defined DataTypes:
The data types that are defined by the user are called the derived datatype
or user-defined derived data type.
These types include:
Class
12
Structure
Union
Enumeration
Typedef defined DataType
Below is the detailed description of the following types:
1. Class: The building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds its
own data members and member functions, which can be accessed and
used by creating an instance of that class. A class is like a blueprint for an
object.
Syntax:
Example:
// Class
#include <bits/stdc++.h>
class Geeks {
// Access specifier
13
public:
// Data Members
string geekname;
// Member Functions()
void printname()
};
int main()
Geeks obj1;
obj1.geekname = "GeeksForGeeks";
obj1.printname();
return 0;
Output:
Geekname is: GeeksForGeeks
2. Structure: A structure is a user defined data type in C/C++. A structure
creates a data type that can be used to group items of possibly different
types into a single type.
Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Example:
// Structures in C++
#include <iostream>
struct Point {
15
int x, y;
};
int main()
arr[0].x = 10;
arr[0].y = 20;
return 0;
Output:
10, 20
3. Union: Like Structures, union is a user defined data type. In union, all
members share the same memory location. For example in the following
C program, both x and y share the same location. If we change x, we can
see the changes being reflected in y.
16
#include <iostream>
union test {
int x, y;
};
int main()
// A union variable t
union test t;
t.x = 2;
<< endl
<< endl;
t.y = 10;
<< endl
<< endl;
return 0;
4. Output:
5. After making x = 2:
6. x = 2, y = 2
7. After making Y = 10:
8. x = 10, y = 10
9. Enumeration: Enumeration (or enum) is a user defined data type in C. It is
mainly used to assign names to integral constants, the names make a
program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};
// of enum in C++
#include <iostream>
Tue,
Wed,
Thur,
Fri,
Sat,
Sun };
int main()
day = Wed;
return 0;
Output:
2
10. Typedef : C++ allows you to define explicitly new data type names by
using the keyword typedef. Using typedef does not actually create a new
data class, rather it defines a name for an existing type. This can increase
the portability(the ability of a program to be used across different types of
machines; i.e., mini, mainframe, micro, etc; without much changes into
the code)of a program as only the typedef statements would have to be
changed. Using typedef one can also aid in self-documenting code by
allowing descriptive names for the standard data types.
Syntax:
typedef type name;
where type is any C++ data type and name is the new name for this data
type.
This defines another name for the standard type of C++.
Example:
#include <iostream>
int main()
{
20
b1 = 'c';
return 0;
Output:
c
Polymorphism:
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a greek word. In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation, and polymorphism.
In the above case, the prototype of display() function is the same in both the base and
derived class. Therefore, the static binding cannot be applied. It would be great if the
appropriate function is selected at the run time. This is known as run time
polymorphism.
It is less flexible as mainly all the things It is more flexible as all the things
execute at the compile time. execute at the run time.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
23
Output:
Eating bread...
1. #include <iostream>
2. using namespace std;
3. class Shape { // base class
4. public:
5. virtual void draw(){ // virtual function
6. cout<<"drawing..."<<endl;
7. }
8. };
9. class Rectangle: public Shape // inheriting Shape class.
10. {
11. public:
12. void draw()
13. {
14. cout<<"drawing rectangle..."<<endl;
15. }
16. };
17. class Circle: public Shape // inheriting Shape class.
24
18.
19. {
20. public:
21. void draw()
22. {
23. cout<<"drawing circle..."<<endl;
24. }
25. };
26. int main(void) {
27. Shape *s; // base class pointer.
28. Shape sh; // base class object.
29. Rectangle rec;
30. Circle cir;
31. s=&sh;
32. s->draw();
33. s=&rec;
34. s->draw();
35. s=?
36. s->draw();
37. }
Output:
drawing...
drawing rectangle...
drawing circle...
1. #include <iostream>
2. using namespace std;
3. class Animal { // base class declaration.
4. public:
5. string color = "Black";
6. };
7. class Dog: public Animal // inheriting Animal class.
25
8. {
9. public:
10. string color = "Grey";
11. };
12. int main(void) {
13. Animal d= Dog();
14. cout<<d.color;
15. }
Output:
Black
Encapsulation:
A key idea in object-oriented programming (OOP) is encapsulation, which permits data
hiding and gives classes a way to isolate their implementation details from their clients.
C++ is an OOP language that provides several features for implementing
encapsulation, such as access specifiers and member functions. In this post, we'll
examine the C++ implementation of the encapsulation principle.
Encapsulation in C++:
The act of encapsulating involves combining data and the methods that manipulate it
into a single entity, referred to as a class. A class in C++ is a user-defined data type
that has member methods and data members. The member functions are methods
that work on the data members, which are variables that hold an object's state.
Access specifiers:
C++ provides three access specifiers, public, private, and protected, to control the
accessibility of class members. Anywhere in the programme can access the members
thanks to the public access specifier. Only the member functions of the class are
permitted access to the members thanks to the private access specifier. The member
functions of the class and its derived classes are able to access the members thanks to
the protected access specifier.
By default, all the members of a class are private. Therefore, we need to specify the
access specifiers explicitly to control the accessibility of the members.
26
Member functions:
Member functions are functions that are defined inside a class and operate on the data
members of that class. Because they are a component of the class, member functions
can access the private members of the class. Member functions can be classified into
two types: accessor functions and mutator functions.
Accessor functions are member functions that provide read-only access to the data
members of a class. Accessor functions do not modify the state of the object. Examples
of accessor functions include get() and display() functions.
Mutator functions are member functions that modify the state of the object by
changing the value of the data members. Mutator functions have access to and control
over a class's private members. Examples of mutator functions include set() and
update() functions.
Data hiding:
Data hiding is an important aspect of encapsulation that enables the data members of
a class to be hidden from the clients of the class. By making the data members private
and enabling accessor and mutator functions to access and modify the data members,
data hiding can be accomplished.
1. #include <iostream>
2. using namespace std;
3.
4. class Employee {
5. private:
6. int empId;
7. string empName;
8. float empSalary;
9.
10. public:
11. void setEmpId(int id) {
12. empId = id;
13. }
14.
15. void setEmpName(string name) {
16. empName = name;
27
17. }
18.
19. void setEmpSalary(float salary) {
20. empSalary = salary;
21. }
22.
23. int getEmpId() {
24. return empId;
25. }
26.
27. string getEmpName() {
28. return empName;
29. }
30.
31. float getEmpSalary() {
32. return empSalary;
33. }
34. };
35.
36. int main() {
37. Employee emp;
38. emp.setEmpId(101);
39. emp.setEmpName("John Doe");
40. emp.setEmpSalary(5000.0);
41.
42. cout << "Employee ID: " << emp.getEmpId() << endl;
43. cout << "Employee Name: " << emp.getEmpName() << endl;
44. cout << "Employee Salary: " << emp.getEmpSalary() << endl;
45.
46. return 0;
47. }
In this example, we have defined a class named Employee that has three private data
members: empId, empName, and empSalary. We have also defined six public member
functions: setEmpId(), setEmpName(), setEmpSalary(), getEmpId(), getEmpName(), and
getEmpSalary().
28
The values of the private data members are set using the set functions, which are
mutator functions. The values of the private data members are retrieved using the get
functions, which are accessor functions.
In the main() function, we have created an object of the Employee class and used the
mutator functions to set the values of the private data members. We have then used
the accessor functions to get the values of the private data members and printed them
to the console.
Output:
In this way, encapsulation is implemented in C++ using access specifiers and member
functions. The private data members are hidden from the outside world, and the public
member functions provide a controlled interface to access and modify them.
Benefits of encapsulation:
Encapsulation provides several benefits, including:
Syntax in C++:
What is Syntax?
Syntax refers to the rules and regulations for writing statements in a
programming language. They can also be viewed as the grammatical rules
defining the structure of a programming language.
The C++ language also has its syntax for the functionalities it provides.
Different statements have different syntax specifying their usage but C++
29
programs also have basic syntax rules that are followed throughout all the
programs.
The image above shows the basic C++ program that contains header files,
main function, namespace declaration, etc. Let’s try to understand them one
by one.
1. Header File
The header files contain the definition of the functions and macros we are
using in our program. They are defined on the top of the C++ program.
In line #1, we used the #include <iostream> statement to tell the compiler
to include an iostream header file library which stores the definition of the
cin and cout methods that we have used for input and output. #include is a
preprocessor directive using which we import header files.
Syntax:
#include <library_name>
2. Namespace
In line #2, we have used the using namespace std statement for specifying
that we will be the standard namespace where all the standard library
functions are defined.
Syntax:
using namespace std;
3. Main Function
Functions are basic building blocks of a C++ program that contains the
instructions for performing some specific task. Apart from the instructions
present in its body, a function definition also contains information about its
return type and parameters. To know more about C++ functions, please refer
to the article Functions in C++.
In line #3, we defined the main function as int main(). The main function is
the most important part of any C++ program. The program execution always
starts from the main function. All the other functions are called from the main
function. In C++, the main function is required to return some value indicating
the execution status.
Syntax:
int main() {
4. Blocks
Blocks are the group of statements that are enclosed within { } braces. They
define the scope of the identifiers and are generally used to enclose the body
of functions and control statements.
The body of the main function is from line #4 to line #9 enclosed within { }.
Syntax:
{
return 0;
}
5. Semicolons
As you may have noticed by now, each statement in the above code is
followed by a ( ; ) semicolon symbol. It is used to terminate each line of the
31
6. Identifiers
We use identifiers for the naming of variables, functions, and other user-
defined data types. An identifier may consist of uppercase and lowercase
alphabetical characters, underscore, and digits. The first letter must be an
underscore or an alphabet.
Example:
int num1 = 24;
int num2 = 34;
num1 & num2 are the identifiers and int is the data type.
7. Keywords
In the C++ programming language, there are some reserved words that are
used for some special meaning in the C++ program. It can’t be used for
identifiers.
For example, the words int, return, and using are some keywords used in
our program. These all have some predefined meaning in the C++ language.
There are total 95 keywords in C++. These are some keywords.
int void if while for
auto bool break
In line #7, we have used the cout method which is the basic output method
in C++ to output the sum of two numbers in the standard output stream
(stdout).
Syntax:
cout << result << endl;
Now, we have a better understanding of the basic syntax structure of the
above C++ program. Let’s try to execute this program and see if it works
correctly.
32
#include <iostream>
// Standard Namespace
// Main Function
int main()
// Declaration of Variable
// Output
33
// Return Statement
return 0;
Output
58
The above program runs correctly and displays the specified output because
we have followed the syntax rules of C++. We will learn more about these
basic elements later.
1. Class
A class is a template of an object. For example, the animal is a class & dog
is the object of the animal class. It is a user-defined data type. A class has its
own attributes (data members) and behavior (member functions). The first
letter of the class name is always capitalized & use the class keyword for
creating the class.
In line #3, we have declared a class named Calculate and its body expands
from line #3 to line #7.
Syntax:
class class_name{
// class body
};
The attributes or data in the class are defined by the data members & the
functions that work on these data members are called the member functions.
Example:
class Calculate{
public:
int num1 = 50; // data member
int num2 = 30; // data member
// member function
int addition() {
int result = num1 + num2;
cout << result << endl;
}
};
In the above example, num1 and num2 are the data member & addition() is a
member function that is working on these two data members. There is a
keyword here public that is access modifiers. The access modifier decides
who has access to these data members & member functions. public access
modifier means these data members & member functions can get access by
anyone.
35
3. Object
The object is an instance of a class. The class itself is just a template that is
not allocated any memory. To use the data and methods defined in the class,
we have to create an object of that class.
They are declared in the similar way we declare variables in C++.
Syntax:
class_name object_name;
We use dot operator ( . ) for accessing data and methods of an object.
Now, let’s execute our code to see the output of the program.
C++
#include <iostream>
class Calculate{
// Access Modifiers
public:
// data member
// memeber function
int addition() {
};
int main() {
// object declaration
Calculate add;
add.addition();
return 0;
Output
80
The memory size of basic data types may change according to 32 or 64 bit operating
system.
38
Let's see the basic data types. It size is given according to 32 bit OS.
float 4 byte
double 8 byte
39
Variable in C++:
A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
1. type variable_list;
1. int x;
2. float y;
3. char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
A variable name can start with alphabet and underscore only. It can't start with digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
1. int a;
2. int _ab;
3. int a30;
1. int 4;
2. int x y;
3. int double;
String in C++:
C++ has in its definition a way to represent a sequence of characters as an
object of the class. This class is called std:: string. The string class stores
the characters as a sequence of bytes with the functionality of
allowing access to the single-byte character.
In the case of strings, memory is allocated The size of the character array has to
dynamically. More memory can be be allocated statically, more memory
allocated at run time on demand. As no cannot be allocated at run time if
memory is preallocated, no memory is required. Unused allocated memory is
wasted. also wasted
Operations on Strings
1) Input Functions
Function Definition
push_back() This function is used to input a character at the end of the string.
Example:
CPP
#include <iostream>
// Driver Code
int main()
// Declaring string
string str;
getline(cin, str);
// Displaying string
// Inserting a character
str.push_back('s');
// Displaying string
// Deleting a character
str.pop_back();
// Displaying string
return 0;
Output
The initial string is :
The string after push_back operation is : s
The string after pop_back operation is :
Time Complexity: O(1)
Space Complexity: O(n) where n is the size of the string
2) Capacity Functions
Function Definition
This function returns the capacity allocated to the string, which can
be equal to or more than the size of the string. Additional space is
capacity()
allocated so that when the new characters are added to the string,
the operations can be done efficiently.
This function changes the size of the string, the size can be
resize()
increased or decreased.
44
Function Definition
This function decreases the capacity of the string and makes it equal
to the minimum capacity of the string. This operation is useful to
shrink_to_fit()
save additional memory if we are sure that no further addition of
characters has to be made.
Example:
CPP
#include <iostream>
// Driver Code
int main()
// Initializing string
// Displaying string
45
str.resize(13);
// Displaying string
<< endl;
// using shrink_to_fit()
str.shrink_to_fit();
46
// Displaying string
return 0;
Output
The initial string is : geeksforgeeks is for geeks
The string after resize operation is : geeksforgeeks
The capacity of string is : 26
The length of the string is :13
The new capacity after shrinking is : 13
Time Complexity: O(1)
Space Complexity: O(n) where n is the size of the string
3) Iterator Functions
Function Definition
end() This function returns an iterator to the next to the end of the string.
rbegin() This function returns a reverse iterator pointing at the end of the string.
Function Definition
This function returns a constant iterator pointing to the next of end of the
cend()
string, it cannot be used to modify the contents it points-to.
Algorithm:
1. Declare a string
2. Try to iterate the string using all types of iterators
3. Try modification of the element of the string.
4. Display all the iterations.
Example:
CPP
#include <iostream>
// Driver Code
48
int main()
// Initializing string`
// Declaring iterator
std::string::iterator it;
std::string::reverse_iterator it1;
cout<<"Str:"<<str<<"\n";
// Displaying string
str = "geeksforgeeks";
": ";
str = "geeksforgeeks";
//Displaying String
cout<<*it2;
cout<<"\n";
str = "geeksforgeeks";
50
cout<<*it3;
cout<<"\n";
return 0;
Output
Str:geeksforgeeks
The string using forward iterators is : Geeksforgeeks
The reverse string using reverse iterators is : Skeegrofskeeg
The string using constant forward iterator is :geeksforgeeks
The reverse string using constant reverse iterator is
:skeegrofskeeg
Time Complexity: O(1)
Space Complexity: O(n) where n is the size of the string
4) Manipulating Functions:
51
Function Definition
Example:
CPP
#include <iostream>
// Driver Code
int main()
char ch[80];
// copies "geeksforgeeks"
str1.swap(str2);
53
return 0;
Output
The new copied character array is : geeksforgeeks
The 1st string before swapping is : geeksforgeeks is for geeks
The 2nd string before swapping is : geeksforgeeks rocks
The 1st string after swapping is : geeksforgeeks rocks
The 2nd string after swapping is : geeksforgeeks is for geeks
Function in C++:
The function in C++ language is also known as procedure or subroutine in other
programming languages.
To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions in C
There are many advantages of functions.
54
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.
2) Code optimization
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number
or not. Without using function, you need to write the prime number logic 3 times. So,
there is repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it
several times.
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C++ header files
such as ceil(x), cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a big
program and optimizes the code.
55
Declaration of a function
The syntax of creating function in C++ language is given below:
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to
handle the application.
In C++, global namespace is the root namespace. The global::std will always refer to
the namespace "std" of C++ Framework.
1. #include <iostream>
2. using namespace std;
3. namespace First {
4. void sayHello() {
5. cout<<"Hello First Namespace"<<endl;
6. }
7. }
8. namespace Second {
9. void sayHello() {
10. cout<<"Hello Second Namespace"<<endl;
11. }
12. }
13. int main()
14. {
15. First::sayHello();
16. Second::sayHello();
17. return 0;
18. }
Output:
1. #include <iostream>
2. using namespace std;
3. namespace First{
4. void sayHello(){
5. cout << "Hello First Namespace" << endl;
6. }
7. }
8. namespace Second{
9. void sayHello(){
10. cout << "Hello Second Namespace" << endl;
11. }
12. }
13. using namespace First;
14. int main () {
15. sayHello();
16. return 0;
17. }
Output:
Exception:
Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by
transferring control to special functions called handlers.
To catch exceptions, a portion of code is placed under exception inspection. This is done by
enclosing that portion of code in a try-block. When an exceptional circumstance arises within that
block, an exception is thrown that transfers the control to the exception handler. If no exception is
thrown, the code continues normally and all handlers are ignored.
An exception is thrown by using the throw keyword from inside the try block. Exception handlers
are declared with the keyword catch, which must be placed immediately after the try block:
58
int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e <<
'\n';
}
return 0;
}
Edit & run on cpp.sh
The code under exception handling is enclosed in a try block. In this example this code simply
throws an exception:
1 throw 20;
A throw expression accepts one parameter (in this case the integer value 20), which is passed as
an argument to the exception handler.
The exception handler is declared with the catch keyword immediately after the closing brace of
the try block. The syntax for catch is similar to a regular function with one parameter. The type
of this parameter is very important, since the type of the argument passed by
the throw expression is checked against it, and only in the case they match, the exception is
caught by that handler.
Multiple handlers (i.e., catch expressions) can be chained; each one with a different parameter
type. Only the handler whose argument type matches the type of the exception specified in
the throw statement is executed.
If an ellipsis (...) is used as the parameter of catch, that handler will catch any exception no
matter what the type of the exception thrown. This can be used as a default handler that catches all
exceptions not caught by other handlers:
1 try {
2 // code here
3 }
4 catch (int param) { cout << "int exception"; }
5 catch (char param) { cout << "char exception"; }
6 catch (...) { cout << "default exception"; }
In this case, the last handler would catch any exception thrown of a type that is
59
After an exception has been handled the program, execution resumes after the try-catch block, not
after the throw statement!.
It is also possible to nest try-catch blocks within more external try blocks. In these cases, we
have the possibility that an internal catch block forwards the exception to its external level. This is
done with the expression throw; with no arguments. For example:
1 try {
2 try {
3 // code here
4 }
5 catch (int n) {
6 throw;
7 }
8 }
9 catch (...) {
10 cout << "Exception occurred";
11 }
Exception specification
Older code may contain dynamic exception specifications. They are now deprecated in C++, but still
supported. A dynamic exception specification follows the declaration of a function, appending
a throw specifier to it. For example:
This declares a function called myfunction, which takes one argument of type char and
returns a value of type double. If this function throws an exception of some type other than int,
the function calls std::unexpected instead of looking for a handler or
calling std::terminate.
If this throw specifier is left empty with no type, this means that std::unexpected is called for
any exception. Functions with no throw specifier (regular functions) never
call std::unexpected, but follow the normal path of looking for their exception handler.
Standard exceptions
The C++ Standard library provides a base class specifically designed to declare objects to be thrown
as exceptions. It is called std::exception and is defined in the <exception> header. This
class has a virtual member function called what that returns a null-terminated character sequence
(of type char *) and that can be overwritten in derived classes to contain some sort of description
of the exception.
int main () {
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << '\n';
}
return 0;
}
Edit & run on cpp.sh
We have placed a handler that catches exception objects by reference (notice the ampersand & after
the type), therefore this catches also classes derived from exception, like our myex object of
type myexception.
All exceptions thrown by components of the C++ Standard library throw exceptions derived from
this exception class. These are:
exception description
Also deriving from exception, header <exception> defines two generic exception types that
can be inherited by custom exceptions to report errors:
exception description
A typical example where standard exceptions need to be checked for is on memory allocation:
The exception that may be caught by the exception handler in this example is a bad_alloc.
Because bad_alloc is derived from the standard base class exception, it can be caught
(capturing by reference, captures all related classes).
Operator in C++:
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc.
62
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator
1. int data=5+10*10;
63
The "data" variable will contain 105 because * (multiplicative operator) is evaluated
before + (additive operator).
Flow Control:
C++ is a programming language from a high level that is widely used for creating
applications and software. One of the most important concepts in C++ programming
is Flow Control, which refers to the ability to direct the flow of a program based on
specific conditions. This allows developers to control how their programs execute and
can help to make them more efficient and effective. In this article, we will see the
different types of flow control available in C++, how they work, and when they are
most appropriate.
Conditional Statements:
Conditional Statements are used in C++ to run a certain piece of program only if a
specific condition is met. There are generally three types of conditional statements in
C++: if, if-else, and switch.
if Statement:
The if statement is the simplest of the three and is used to run a certain piece of code
nly if a certain condition is true. For example:
C++ Code:
1. int x = 5;
2. if (x == 5) {
3. std::cout << "x is 5" << std::endl;
4. }
In this example, the block of code inside the curly braces will only be executed if the
condition inside the parentheses is true.
if-else Statement:
The if-else statement is used when we want to execute some code only if some
condition exists. If the given condition is true then code will be executed otherwise
else statement will be used to run other part of the code.For example:
C++ Code:
1. int x = 5;
2. if (x == 5) {
3. std::cout << "x is 5" << std::endl;
65
4. } else {
5. std::cout << "x is not 5" << std::endl;
6. }
In this example, if the condition inside the parentheses is true, the first block of code
will be executed. Otherwise, the second block of code will be executed.
switch Statement:
The switch statement is used to execute different blocks of code based on the value
of a variable. For example:
Pseudo Code:
1. switch (variable) {
2. case value1:
3. // code to execute if the variable is equal to value1
4. break;
5. case value2:
6. // code to execute if the variable is equal to value2
7. break;
8. // add more cases as needed
9. default:
10. // code to execute if the variable does not match any case
11. }
C++ code:
1. int x = 2;
2. switch (x) {
3. case 1:
4. std::cout << "x is 1" << std::endl;
5. break;
6. case 2:
7. std::cout << "x is 2" << std::endl;
8. break;
9. default:
10. std::cout << "x is not 1 or 2" << std::endl;
11. break;
66
12. }
In this example, the switch statement will execute the block of code associated with
the value of x. If x is 1, the first block of code will be executed. If x is 2, the second block
of code will be executed. If x is any other value, the default block of code will be
executed.
Loops:
Loops are used in C++ to execute a block of code multiple times, either until a certain
condition is met or for a specific number of times. There are generally three types of
loops in C++: while, do-while, and for.
While Loop:
The while loop is used to execute when we want to run some code for until some
specific condition matches. For example:
C++ Code:
1. int x = 0;
2. while (x < 5) {
3. std::cout << x << std::endl;
4. x++;
5. }
In this example, the while loop will continue to execute the block of code inside the
curly braces as long as x is less than 5. Each time the loop executes, the value of x will
be incremented by 1.
do-while Loop:
The do-while loop is the same as the while loop, but the condition is checked after
the first iteration of the loop. For example:
C++ Code:
1. int x = 0;
2. do {
3. std::cout << x << std::endl;
4. x++;
5. } while (x < 5);
67
In this example, the do-while loop will execute the block of code inside the curly
brackets, and then it will check the condition. So it will be executed a minimum of one
time.
for Loop:
The for loop allows a program to execute a piece of program a fixed number of times.
The syntax for the for loop is:
Pseudo Code:
Here is an example that uses the for loop to print the numbers from 1 to 10:
C++ Code:
Recursion:
When function is called within the same function, it is known as recursion in C++. The
function which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is known as
tail recursion. In tail recursion, we generally call the same function with return
statement.
1. recursionfunction(){
2. recursionfunction(); //calling self function
3. }
68
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int factorial(int);
6. int fact,value;
7. cout<<"Enter any number: ";
8. cin>>value;
9. fact=factorial(value);
10. cout<<"Factorial of a number is: "<<fact<<endl;
11. return 0;
12. }
13. int factorial(int n)
14. {
15. if(n<0)
16. return(-1); /*Wrong value*/
17. if(n==0)
18. return(1); /*Terminating condition*/
19. else
20. {
21. return(n*factorial(n-1));
22. }
23. }
Output:
We can understand the above program of recursive method call by the figure given
below:
69
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
11. }
Output:
10
0
20
0
30
We can also traverse the array elements using foreach loop. It returns array element
one by one.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"\n";
10. }
11. }
Output:
10
20
30
40
50
For example,
72
The array x in this case is 6 elements wide. But we've only given it a three-element
initialization.
When that happens, the compiler fills in the empty spaces with random values. This
random value frequently appears as 0.
The address of the subsequent element, x[1], will then be 2124, followed by x[2], 2128,
and so forth.
Each element in this case has a four-fold increase in size. This is due to the fact that int
has a 4 byte capacity.
As you can see, the components are arranged in a two-dimensional array using rows
and columns; there are I number of rows and j number of columns.
Output:
Output:
Pointer:
The pointer in C++ language is a variable, it is also known as locator or indicator that
points to an address of a value.
Syntax
1. datatype *var_name;
2. int *ptr; // ptr can point to an address which holds int data
Since the data type knows how many bytes the information is held in, we associate it
with a reference. The size of the data type to which a pointer points is added when we
increment a pointer.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees etc. and used with arrays, structures and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many usage of pointers in C++ language.
Pointers in c language are widely used in arrays, functions and structures. It reduces
the code and improves the performance.
Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).
Pointer Example
Let's see the simple example of using pointers printing the address and value.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int number=30;
77
6. int ∗ p;
7. p=&number;//stores the address of number variable
8. cout<<"Address of number variable is:"<<&number<<endl;
9. cout<<"Address of p variable is:"<<p<<endl;
10. cout<<"Value of p variable is:"<<*p<<endl;
11. return 0;
12. }
Output:
Output:
1. int *ptr1;
2. int arr[10];
3. int *ptr2 = arr+20;
Here, ptr1 is not initialized, making it invalid, and ptr2 is outside of the bounds of arr,
making it likewise weak. (Take note that not all build failures are caused by faulty
references.)
1. int *ptr1 = 0;
2. int *ptr2 = NULL;
1. char a;
2. char *b;
3. char ** c;
4. a = 'g';
79
5. b = &a;
6. c = &b;
Here b points to a char that stores 'g', and c points to the pointer b.
Example
1. #include
2. using namespace std;
3. // Pass-by-Value
4. int square1(int n)
5. {cout << "address of n1 in square1(): " << &n << "\n";
6. n *= n;
7. return n;
8. }
9. // Pass-by-Reference with Pointer Arguments
10. void square2(int* n)
11. {
12. cout << "address of n2 in square2(): " << n << "\n";
13. *n *= *n;
14. }
15. // Pass-by-Reference with Reference Arguments
16. void square3(int& n)
17. {
18.
19. cout << "address of n3 in square3(): " << &n << "\n";
20. n *= n;
21. }
22. void example()
23. {
24. // Call-by-Value
25. int n1 = 8;
80
26. cout << "address of n1 in main(): " << &n1 << "\n";
27. cout << "Square of n1: " << square1(n1) << "\n";
28. cout << "No change in n1: " << n1 << "\n";
29.
30. // Call-by-Reference with Pointer Arguments
31. int n2 = 8;
32. cout << "address of n2 in main(): " << &n2 << "\n";
33. square2(&n2);
34. cout << "Square of n2: " << n2 << "\n";
35. cout << "Change reflected in n2: " << n2 << "\n";
36.
37. // Call-by-Reference with Reference Arguments
38. int n3 = 8;
39. cout << "address of n3 in main(): " << &n3 << "\n";
40. square3(n3);
41. cout << "Square of n3: " << n3 << "\n";
42. cout << "Change reflected in n3: " << n3 << "\n";
43. }
44. // Driver program
45. int main() { example(); }
Output
81
Structure:
In C++, classes and structs are blueprints that are used to create the instance of a class.
Structs are used for lightweight objects such as Rectangle, color, Point, etc.
Unlike class, structs in C++ are value type than reference type. It is useful if you have
data that is not intended to be modified after creation of struct.
C++ Structure is a collection of different data types. It is similar to the class that holds
different types of data.
1. struct structure_name
2. {
3. // member declarations.
4. }
1. struct Student
2. {
3. char name[20];
4. int id;
5. int age;
6. }
In the above case, Student is a structure contains three variables name, id, and age.
When the structure is declared, no memory is allocated. When the variable of a
structure is created, then the memory is allocated. Let's understand this scenario.
Student s;
Here, s is a structure variable of type Student. When the structure variable is created,
the memory will be allocated. Student structure contains one char variable and two
integer variable. Therefore, the memory for one char variable is 1 byte and two ints will
be 2*4 = 8. The total memory occupied by the s variable is 9 byte.
For example:
1. s.id = 4;
In the above statement, we are accessing the id field of the structure Student by using
the dot(.) operator and assigns the value 4 to the id field.
1. #include <iostream>
2. using namespace std;
3. struct Rectangle
83
4. {
5. int width, height;
6.
7. };
8. int main(void) {
9. struct Rectangle rec;
10. rec.width=8;
11. rec.height=5;
12. cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;
13. return 0;
14. }
Output:
1. #include <iostream>
2. using namespace std;
3. struct Rectangle {
4. int width, height;
5. Rectangle(int w, int h)
6. {
7. width = w;
8. height = h;
9. }
10. void areaOfRectangle() {
11. cout<<"Area of Rectangle is: "<<(width*height); }
12. };
13. int main(void) {
14. struct Rectangle rec=Rectangle(4,6);
15. rec.areaOfRectangle();
16. return 0;
17. }
84
Output:
Structure Class
The instance of the structure is known as The instance of the class is known as
"Structure variable". "Object of the class".
85
SECTION-II
Abstracting Mechanism
Classes:
In C++, class is a group of similar objects. It is a template from which objects are
created. It can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
86
15. }
Output:
201
Sonoo Jaiswal
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }
87
Output:
201 Sonoo
202 Nakul
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }
88
Output:
Public:
All the class members declared under public will be available to everyone.
The data members and member functions declared public can be accessed
by other classes too. The public members of a class can be accessed from
anywhere in the program using the direct member access operator (.) with
the object of that class.
Example:
// access modifier
#include <iostream>
// class definition
class Circle {
public:
double radius;
double compute_area()
89
};
// main function
int main()
Circle obj;
obj.radius = 5.5;
return 0;
Output:
Radius is: 5.5
Area is: 94.985
In the above program, the data member radius is public so we are allowed to
access it outside the class.
90
Private:
The class members declared as private can be accessed only by the
functions inside the class. They are not allowed to be accessed directly by
any object or function outside the class. Only the member functions or the
friend functions are allowed to access the private data members of a class.
Example:
// access modifier
#include <iostream>
class Circle {
private:
double radius;
public:
void compute_area(double r)
radius = r;
};
// main function
int main()
Circle obj;
obj.compute_area(1.5);
return 0;
}
92
Output:
Radius is: 1.5
Area is: 7.065
Difference between Public and Private
Public Private
Constructor:
A constructor is a particular member function having the same name as the class name.
It calls automatically whenever the object of the class is created.
Syntax:
The syntax of the constructor in C++ are given below.
1. class class_name
2. {
3. ……….
4. public
93
In the above-given syntax, class_name is the constructor's name, the public is an access
specifier, and the parameter list is optional.
Example of Constructor:
1. #include <iostream.h>
2. #include <conio.h>
3. using namespace std;
4. class hello { // The class
5. public: // Access specifier
6. hello () { // Constructor
7. cout << "Hello World! Program in C++ by using Constructor";
8. }
9. void display() {
10. cout <<"Hello World!" <<endl;
11. }
12. };
13. int main() {
14. hello myObj; /
15. return 0;
16. }
o Default constructor
o Dynamic constructor
o Parameterized constructor
o Copy constructor
1. class class_name {
2. private:
3. ………..
4. ………..
5. public:
6. class_name ()
7. {
8. …….
9. }
10. }
If no constructor is defined in the class, the compiler automatically creates the class's
default constructor.
Example:
1. class student {
2. private:
3. ………..
4. ………..
5. public:
6. student ()
7. {
8. …….
9. }
10. }
hello::hello()
1. Class classname
2. {
95
3. …………;
4. …………;
5. Public:
6. Class name (parameter list)
7. {
8. ………….;
9. }
10. };
Copy Constructor: A particular constructor used for the creation of an existing object.
The copy constructor is used to initialize the thing from another of the same type.
Syntax:
In the above syntax, the object refers to a thing used to initialize another object.
Dynamic Constructor: This type of constructor can be used to allocate the memory
while creating the objects. The data members of an object after creation can be
initialized, called dynamic initialization.
Destructor in C++?
Destructors have the same class name preceded by (~) tilde symbol. It removes and
destroys the memory of the object, which the constructor allocated during the creation
of an object.
Syntax:
The syntax of destructor in C++ are given below.
1. class class_name
96
2. {
3. …………….;
4. …………….;
5. public:
6. xyz(); //constructor
7. ~xyz(); //destructor
8. };
Here, we use the tilde symbol for defining the destructor in C++ programming.
The Destructor has no argument and does not return any value, so it cannot be
overloaded.
Example of Destructor:
1. #include <iostream.h>
2. #include <conio.h>
3. using namespace std;
4. class Hello {
5. public:
6. //Constructor
7. Hello () {
8. cout<< "Constructor function is called" <<endl;
9. }
10. //Destructor
11. ~Hello () {
12. cout << "Destructor function is called" <<endl;
13. }
14. //Member function
15. void display() {
16. cout <<"Hello World!" <<endl;
17. }
18. };
19. int main(){
20. //Object created
21. Hello obj;
22. //Member function called
23. obj.display();
24. return 0;
97
25. }
Arguments It may or may not contain arguments. It cannot contain the arguments.
Return type It has return types. It doesn't have any return type.
In numbers We can use more than one We cannot use more than one
constructor in our program. destructor in the program.
o Default constructor
o Copy constructor
o Parameterized constructor
o Dynamic constructor
Declaration The following declaration is used for The following declaration is used
creating a constructor: for creating a destructor:
class class_name class class_name
{ {
………. …………….;
public …………….;
class_name ([parameter list]) public:
{ ~xyz();
………………. {
} …………
}; };
Member Function:
A class member function is a function that, like any other variable, is defined or
prototyped within the class declaration. It has access to all the members of the class
and can operate on any object of that class.
Let us use a member function to access the members of a previously created class
instead of directly accessing them.
1. class Dice {
2. public:
3. double L; // a dice's length
4. double B; // a dice's breadth
5. double H; // a dice's height
6. double getVolume(void); // Returns dice volume
7. };
99
Member functions can be defined either within the class definition or separately with
the scope resolution operator,:. Even if the inline specifier is not used, specifying a
member function within the class declaration declares the function inline. So, you may
either define the Volume() function as shown below.
1. class Dice {
2. public:
3. double L; // a dice's length
4. double B; // a dice's breadth
5. double H; // a dice's height
6. double getVolume(void) {
7. return L * B * H;
8. }
9. };
If we want, we may define the identical function outside of the class using the scope
resolution operator (::), as seen below.
1. double Dice::getVolume(void) {
2. return L * B * H;
3. }
The main thing to remember here is that we must use the class name exactly before
the :: operator. The dot operator (.) will be used to perform a member function on an
object and will only manipulate data relevant to that object as follows:
Let us apply the techniques discussed above to set and get the values of various class
members of a class.
C++ Program:
1. #include <iostream>
2.
3. using namespace std;
4.
5. class Dice {
6. public:
7. double L; // a dice's length
100
Output:
Static Members:
The static is a keyword in the C and C++ programming language. We use the static
keyword to define the static data member or static member function inside and outside
of the class. Let's understand the static data member and static member function using
the programs.
102
Syntax
The data_type is the variable type in C++, such as int, float, string, etc.
Example 1: Let's create a simple program to access the static data members in the
C++ programming language.
1. #include <iostream>
2. #include <string.h>
3. using namespace std;
4. // create class of the Car
5. class Car
6. {
7. private:
8. int car_id;
9. char car_name[20];
10. int marks;
11.
12. public:
13. // declare a static data member
14. static int static_member;
15.
16. Car()
17. {
18. static_member++;
19. }
103
20.
21. void inp()
22. {
23. cout << " \n\n Enter the Id of the Car: " << endl;
24. cin >> car_id; // input the id
25. cout << " Enter the name of the Car: " << endl;
26. cin >> car_name;
27. cout << " Number of the Marks (1 - 10): " << endl;
28. cin >> marks;
29. }
30.
31. // display the entered details
32. void disp ()
33. {
34. cout << " \n Id of the Car: " << car_id;
35. cout << "\n Name of the Car: " << car_name;
36. cout << " \n Marks: " << marks;
37.
38. }
39. };
40.
41. // initialized the static data member to 0
42. int Car::static_member = 0;
43.
44. int main ()
45. {
46. // create object for the class Car
47. Car c1;
48. // call inp() function to insert values
49. c1. inp ();
50. c1. disp();
51.
52. //create another object
53. Car c2;
54. // call inp() function to insert values
55. c2. inp ();
56. c2. disp();
104
57.
58.
59. cout << " \n No. of objects created in the class: " << Car :: static_member <<endl;
60. return 0;
61. }
Output
Syntax
1. class_name::function_name (parameter);
function_name: The function name is the name of the static member function.
parameter: It defines the name of the pass arguments to the static member function.
105
Example 2: Let's create another program to access the static member function using
the class name in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
6. static int num;
7.
8. public:
9. // create static member function
10. static int func ()
11. {
12. return num;
13. }
14. };
15. // initialize the static data member using the class name and the scope resolution operator
16. int Note :: num = 5;
17.
18. int main ()
19. {
20. // access static member function using the class name and the scope resolution
21. cout << " The value of the num is: " << Note:: func () << endl;
22. return 0;
23. }
Output
Example 3: Let's create another program to access the static member function using
the class' object in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
106
Output
Example 4: Let's consider an example to access the static member function using the
object and class in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3. class Member
4. {
5.
6. private:
7. // declaration of the static data members
8. static int A;
9. static int B;
10. static int C;
107
11.
12. // declare public access specifier
13. public:
14. // define the static member function
15. static void disp ()
16. {
17. cout << " The value of the A is: " << A << endl;
18. cout << " The value of the B is: " << B << endl;
19. cout << " The value of the C is: " << C << endl;
20. }
21. };
22. // initialization of the static data members
23. int Member :: A = 20;
24. int Member :: B = 30;
25. int Member :: C = 40;
26.
27. int main ()
28. {
29. // create object of the class Member
30. Member mb;
31. // access the static member function using the class object name
32. cout << " Print the static member through object name: " << endl;
33. mb. disp();
34. // access the static member function using the class name
35. cout << " Print the static member through the class name: " << endl;
36. Member::disp();
37. return 0;
38. }
Output
References:
When a variable is declared as a reference, it becomes an alternative name
for an existing variable. A variable can be declared as a reference by putting
‘&’ in the declaration.
Also, we can define a reference variable as a type of variable that can act as
a reference to another variable. ‘&’ is used for signifying the address of a
variable or any memory. Variables associated with reference variables can
be accessed either by its name or by the reference variable associated with
it.
Prerequisite: Pointers in C++
Syntax:
data_type &ref = variable;
Example:
C++
// use of references
#include <iostream>
int main()
int x = 10;
// ref is a reference to x.
int& ref = x;
109
ref = 20;
x = 30;
return 0;
Output:
x = 20
ref = 30
Applications of Reference in C++
There are multiple applications for references in C++, a few of them are
mentioned below:
1. Modify the passed parameters in a function
2. Avoiding a copy of large structures
3. In For Each Loop to modify all objects
4. For Each Loop to avoid the copy of objects
1. Modify the passed parameters in a function:
If a function receives a reference to a variable, it can modify the value of the
variable. For example, the following program variables are swapped using
references.
Example:
C++
#include <iostream>
// references
first = second;
second = temp;
// Driver function
int main()
// Variables declared
int a = 2, b = 3;
// function called
swap(a, b);
111
return 0;
Output
3 2
2. Avoiding a copy of large structures:
Imagine a function that has to receive a large object. If we pass it without
reference, a new copy of it is created which causes a waste of CPU time and
memory. We can use references to avoid this.
Example:
struct Student {
string name;
string address;
int rollNo;
}
// using references
#include <iostream>
#include <vector>
// Driver code
int main()
// use reference
x = x + 5;
}
113
// Printing elements
return 0;
Output
15 25 35 45
4. For Each Loop to avoid the copy of objects:
We can use references in each loop to avoid a copy of individual objects
when objects are large.
Example:
C++
// copy of objects
#include <iostream>
#include <vector>
114
// Driver code
int main()
// Declaring vector
"geeksforgeeks write",
"geeksforgeeks ide" };
return 0;
Output
geeksforgeeks practice
geeksforgeeks write
geeksforgeeks ide
115
References vs Pointers
Both references and pointers can be used to change the local variables of
one function inside another function. Both of them can also be used to save
copying of big objects when passed as arguments to functions or returned
from functions, to get efficiency gain. Despite the above similarities, there are
the following differences between references and pointers.
1. A pointer can be declared as void but a reference can never be void For
example
int a = 10;
void* aa = &a; // it is valid
void& ar = a; // it is not valid
2. The pointer variable has n-levels/multiple levels of indirection i.e. single-
pointer, double-pointer, triple-pointer. Whereas, the reference variable has
only one/single level of indirection. The following code reveals the mentioned
points:
3. Reference variables cannot be updated.
4. Reference variable is an internal pointer.
5. Declaration of a Reference variable is preceded with the ‘&’ symbol ( but
do not read it as “address of”).
Example:
C++
#include <iostream>
// Driver Code
int main()
int i = 10;
// single pointer
int* p = &i;
// double pointer
int** pt = &p;
// triple pointer
// or point to.
int a = 5;
int& S = a;
117
int& S0 = S;
int& S1 = S0;
return 0;
Output
i = 10 p = 0x7ffecfe7c07c pt = 0x7ffecfe7c080 ptr =
0x7ffecfe7c088
a = 5 S = 5 S0 = 5 S1 = 5
Limitations of References
#include <iostream>
int& fun()
return x;
int main()
{
119
fun() = 30;
return 0;
Output
30
Question 2
C++
#include <iostream>
int main()
return 0;
Output:
./3337ee98-ae6e-4792-8128-7c879288221f.cpp: In function 'int
main()':
./3337ee98-ae6e-4792-8128-7c879288221f.cpp:8:19: error: invalid
initialization of non-const reference of type 'int&' from an rvalue
of type 'int'
cout << fun(10);
120
^
./3337ee98-ae6e-4792-8128-7c879288221f.cpp:4:5: note: in passing
argument 1 of 'int fun(int&)'
int fun(int& x) { return x; }
Question 3
C++
#include <iostream>
str1 = str2;
str2 = temp;
int main()
swap(str1, str2);
return 0;
Output
str1 is FOR GEEKS
str2 is GEEKS
Question 4
C++
#include <iostream>
int main()
int x = 10;
Output:
./18074365-ebdc-4b13-81f2-cfc42bb4b035.cpp: In function 'int
main()':
./18074365-ebdc-4b13-81f2-cfc42bb4b035.cpp:8:11: error: cannot
declare pointer to 'int&'
int&* ptr1 = ptr;
Question 5
C++
122
#include <iostream>
int main()
Output:
timeout: the monitored command dumped core
/bin/bash: line 1: 34 Segmentation fault timeout 15s
./372da97e-346c-4594-990f-14edda1f5021 < 372da97e-346c-4594-990f-
14edda1f5021.in
Question 6
C++
#include <iostream>
int& fun()
int x = 10;
123
return x;
int main()
fun() = 30;
return 0;
Output
0
124
Memory Management
New:
new operator
The new operator denotes a request for memory allocation on the Free Store.
If sufficient memory is available, a new operator initializes the memory and
returns the address of the newly allocated and initialized memory to the pointer
variable.
Syntax to use new operator
pointer-variable = new data-type;
Here, the pointer variable is the pointer of type data-type. Data type could be
any built-in data type including array or any user-defined data type including
structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
struct cust
int p;
cust(int q) : p(q) {}
cust() = default;
};
int main()
//OR
return 0;
Delete:
Since it is the programmer’s responsibility to deallocate dynamically allocated
memory, programmers are provided delete operator in C++ language.
Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;
Here, the pointer variable is the pointer that points to the data object created
by new.
Examples:
delete p;
delete q;
To free the dynamically allocated array pointed by pointer variable, use the
following form of delete:
// Release block of memory
// pointed by pointer-variable
delete[] pointer-variable;
Example:
CPP
#include <iostream>
int main ()
128
int* p = NULL;
p = new(nothrow) int;
if (!p)
else
*p = 29;
int n = 5;
if (!q)
else
q[i] = i+1;
delete p;
delete r;
delete[] q;
130
return 0;
Output
Value of p: 29
Value of r: 75.25
Value store in block of memory: 1 2 3 4 5
Time Complexity: O(n), where n is the given memory size.
Object Copying:
object copying is creating a copy of an existing object, a unit of data in object-oriented
programming. The resulting object is called an object copy or simply copy of the original object.
Copying is basic but has subtleties and can have significant overhead. There are several ways to
copy an object, most commonly by a copy constructor or cloning. Copying is done mostly so the
copy can be modified or moved, or the current value preserved. If either of these is unneeded, a
reference to the original data is sufficient and more efficient, as no copying occurs.
Objects in general store composite data. While in simple cases copying can be done by
allocating a new, uninitialized object and copying all fields (attributes) from the original object, in
more complex cases this does not result in desired behavior.
Methods of copying
The design goal of most objects is to give the resemblance of being made out of one monolithic
block even though most are not. As objects are made up of several different parts, copying
becomes nontrivial. Several strategies exist to treat this problem.
Consider an object A, which contains fields xi (more concretely, consider if A is a string and xi is
an array of its characters). There are different strategies for making a copy of A, referred to
as shallow copy and deep copy. Many languages allow generic copying by one or either strategy,
defining either one copy operation or separate shallow copy and deep copy operations.[1] Note
that even shallower is to use a reference to the existing object A, in which case there is no new
object, only a new reference.
The terminology of shallow copy and deep copy dates to Smalltalk-80.[2] The same distinction
holds for comparing objects for equality: most basically there is a difference between identity
(same object) and equality (same value), corresponding to shallow equality and (1 level) deep
equality of two object references, but then further whether equality means comparing only the
fields of the object in question or dereferencing some or all fields and comparing their values in
turn (e.g., are two linked lists equal if they have the same nodes, or if they have same
values?).[clarification needed]
131
Shallow copy[edit]
One method of copying an object is the shallow copy. In that case a new object B is created, and
the fields values of A are copied over to B.[3][4][5] This is also known as a field-by-field
copy,[6][7][8] field-for-field copy, or field copy.[9] If the field value is a reference to an object (e.g., a
memory address) it copies the reference, hence referring to the same object as A does, and if
the field value is a primitive type it copies the value of the primitive type. In languages without
primitive types (where everything is an object), all fields of the copy B are references to the same
objects as the fields of original A. The referenced objects are thus shared, so if one of these
objects is modified (from A or B), the change is visible in the other. Shallow copies are simple
and typically cheap, as they can usually be implemented by simply copying the bits exactly.
Deep copy[edit]
An alternative is a deep copy, meaning that fields are dereferenced: rather than references to
objects being copied, new copy objects are created for any referenced objects, and references to
these are placed in B.
Implementation
Nearly all object-oriented programming languages provide some way to copy objects. As most
languages do not provide most objects for programs, a programmer must define how an object
should be copied, just as they must define if two objects are identical or even comparable in the
first place. Many languages provide some default behavior.
How copying is solved varies from language to language, and what concept of an object it has.
Lazy copy
A lazy copy is an implementation of a deep copy. When initially copying an object, a (fast)
shallow copy is used. A counter is also used to track how many objects share the data. When the
program wants to modify an object, it can determine if the data is shared (by examining the
counter) and can do a deep copy if needed.
132
Lazy copy looks to the outside just as a deep copy, but takes advantage of the speed of a
shallow copy whenever possible. The downside are rather high but constant base costs because
of the counter. Also, in certain situations, circular references can cause problems.
Lazy copy is related to copy-on-write.
Copy Constructor:
A Copy constructor is an overloaded constructor used to declare and initialize an
object from another object.
1. class A
2. {
3. A(A &x) // copy constructor.
4. {
5. // copyconstructor.
6. }
7. }
In the above case, copy constructor can be called in the following ways:
133
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. int x;
7. A(int a) // parameterized constructor.
8. {
9. x=a;
10. }
11. A(A &i) // copy constructor
12. {
13. x = i.x;
14. }
15. };
16. int main()
17. {
18. A a1(20); // Calling the parameterized constructor.
19. A a2(a1); // Calling the copy constructor.
20. cout<<a2.x;
21. return 0;
22. }
Output:
20
o When we initialize the object with another existing object of the same class type. For
example, Student s1 = s2, where Student is the class.
134
o When the object of the same class type is passed by value as an argument.
o When the function returns the object of the same class type by value.
o Deep copy
Shallow Copy
o The default copy constructor can only produce the shallow copy.
o A Shallow copy is defined as the process of creating the copy of an object by copying
data of all the member variables as it is.
1. #include <iostream>
2.
3. using namespace std;
4.
5. class Demo
6. {
7. int a;
8. int b;
9. int *p;
10. public:
11. Demo()
12. {
13. p=new int;
14. }
15. void setdata(int x,int y,int z)
16. {
17. a=x;
18. b=y;
19. *p=z;
20. }
21. void showdata()
22. {
135
Output:
value of a is : 4
value of b is : 5
value of *p is : 7
In the above case, a programmer has not defined any constructor, therefore, the
statement Demo d2 = d1; calls the default constructor defined by the compiler. The
default constructor creates the exact copy or shallow copy of the existing object. Thus,
the pointer p of both the objects point to the same memory location. Therefore, when
the memory of a field is freed, the memory of another field is also automatically freed
as both the fields point to the same memory location. This problem is solved by
the user-defined constructor that creates the Deep copy.
Deep copy
Deep copy dynamically allocates the memory for the copy and then copies the actual
value, both the source and copy have distinct memory locations. In this way, both the
136
source and copy are distinct and will not share the same memory location. Deep copy
requires us to write the user-defined constructor.
1. #include <iostream>
2. using namespace std;
3. class Demo
4. {
5. public:
6. int a;
7. int b;
8. int *p;
9.
10. Demo()
11. {
12. p=new int;
13. }
14. Demo(Demo &d)
15. {
16. a = d.a;
17. b = d.b;
18. p = new int;
19. *p = *(d.p);
20. }
21. void setdata(int x,int y,int z)
22. {
23. a=x;
24. b=y;
25. *p=z;
26. }
27. void showdata()
28. {
29. std::cout << "value of a is : " <<a<< std::endl;
30. std::cout << "value of b is : " <<b<< std::endl;
31. std::cout << "value of *p is : " <<*p<< std::endl;
32. }
33. };
137
Output:
value of a is : 4
value of b is : 5
value of *p is : 7
In the above case, a programmer has defined its own constructor, therefore the
statement Demo d2 = d1; calls the copy constructor defined by the user. It creates
the exact copy of the value types data and the object pointed by the pointer p. Deep
copy does not create the copy of a reference type variable.
It initializes the new object with the existing It assigns the value of one object
object. to another object.
138
Both the existing object and new object shares Both the existing object and new
the different memory locations. object shares the same memory
location.
If a programmer does not define the copy If we do not overload the "="
constructor, the compiler will automatically operator, the bitwise copy will
generate the implicit default copy constructor. occur.
Assignment Operator:
139
Assignment operators are used to assigning value to a variable. The left side
operand of the assignment operator is a variable and right side operand of
the assignment operator is a value. The value on the right side must be of
the same data-type of the variable on the left side otherwise the compiler will
raise an error.
Different types of assignment operators are shown below:
“=”: This is the simplest assignment operator. This operator is used to
assign the value on the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
“+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator
first adds the current value of the variable on left to the value on the right
and then assigns the result to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
“-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator
first subtracts the current value of the variable on left from the value on
140
the right and then assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
“*=”This operator is combination of ‘*’ and ‘=’ operators. This operator
first multiplies the current value of the variable on left to the value on the
right and then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
“/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right
and then assigns the result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
Below example illustrates the various Assignment Operators:
C
C++
// C program to demonstrate
#include <stdio.h>
int main()
// Assigning value 10 to a
141
int a = 10;
a += 10;
a -= 10;
a *= 10;
a /= 10;
142
return 0;
Output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10
This Input/Output:
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.
143
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(<<).
C++
#include <iostream>
int main()
cout << sample << " - A computer science portal for geeks";
return 0;
Output:
GeeksforGeeks - A computer science portal for geeks
Time Complexity: O(1)
Auxiliary Space: O(1)
145
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 the
screen.
standard input stream (cin): Usually the input device in a computer is
the keyboard. C++ cin statement is the instance of the class istream 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.
C++
#include <iostream>
int main()
int age;
return 0;
Input :
18
Output:
146
#include <iostream>
int main()
return 0;
Output:
An error occurred
Time Complexity: O(1)
Auxiliary Space: O(1)
147
#include <iostream>
int main()
return 0;
Output:
An error occurred
Time Complexity: O(1)
Auxiliary Space: O(1)
148
SECTION-III
INHERIATANCE AND POLYMORPHISM
class BaseClass{
// members....
// member function
}
Syntax:
Syntax: class DerivedClass :
class BaseClass{ access_specifier BaseClass{
// members…. // members….
4. // member function // member function
} }
CPP
#include <iostream>
class Base {
public:
int a;
};
public:
int b;
};
// Driver Code
int main()
Derived geeks;
geeks.b = 3;
geeks.a = 4;
return 0;
Output:
Value from derived class: 3
Value from base class: 4
In C++, the class which inherits the members of another class is called derived class
and the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
Types Of Inheritance
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
152
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
Where,
visibility mode: The visibility mode specifies whether the features of the base class
are publicly inherited or privately inherited. It can be public or private.
o When the base class is privately inherited by the derived class, public members of the
base class becomes the private members of the derived class. Therefore, the public
members of the base class are not accessible by the objects of the derived class only
by the member functions of the derived class.
153
o When the base class is publicly inherited by the derived class, public members of the
base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the derived class as well as
by the member functions of the base class.
Note:
o In C++, the default mode of visibility is private.
o The private members of the base class are never inherited.
Where 'A' is the base class, and 'B' is the derived class.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
154
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }
Output:
Salary: 60000
Bonus: 5000
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
155
19. d1.bark();
20. return 0;
21. }
Output:
Eating...
Barking...
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int a = 4;
6. int b = 5;
7. public:
8. int mul()
9. {
10. int c = a*b;
11. return c;
12. }
13. };
14.
15. class B : private A
16. {
17. public:
18. void display()
19. {
20. int result = mul();
21. std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
22. }
23. };
24. int main()
25. {
26. B b;
27. b.display();
28.
156
29. return 0;
30. }
Output:
Multiplication of a and b is : 20
In the above example, class A is privately inherited. Therefore, the mul() function of
class 'A' cannot be accessed by the object of class B. It can only be accessed by the
member function of class B.
C++ introduces a third visibility modifier, i.e., protected. The member which is
declared as protected will be accessible to all the member functions within the class as
well as the class immediately derived from it.
o Public: When the member is declared as public, it is accessible to all the functions of
the program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own
class as well as the class immediately derived from it.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
158
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }
Output:
Eating...
Barking...
Weeping...
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
160
22. }
23. };
24. class C : public A,public B
25. {
26. public:
27. void display()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is : "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }
Output:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.
1. #include <iostream>
2. using namespace std;
3. class A
161
4. {
5. public:
6. void display()
7. {
8. std::cout << "Class A" << std::endl;
9. }
10. };
11. class B
12. {
13. public:
14. void display()
15. {
16. std::cout << "Class B" << std::endl;
17. }
18. };
19. class C : public A, public B
20. {
21. void view()
22. {
23. display();
24. }
25. };
26. int main()
27. {
28. C c;
29. c.display();
30. return 0;
31. }
Output:
o The above issue can be resolved by using the class resolution operator with the
function. In the above example, the derived class code can be rewritten as:
3. void view()
4. {
5. A :: display(); // Calling the display() function of class A.
6. B :: display(); // Calling the display() function of class B.
7.
8. }
9. };
1. class A
2. {
3. public:
4. void display()
5. {
6. cout<<?Class A?;
7. }
8. } ;
9. class B
10. {
11. public:
12. void display()
13. {
14. cout<<?Class B?;
15. }
16. } ;
In the above case, the function of the derived class overrides the method of the base
class. Therefore, call to the display() function will simply call the function defined in the
derived class. If we want to invoke the base class function, we can use the class
resolution operator.
1. int main()
2. {
3. B b;
4. b.display(); // Calling the display() function of B class.
5. b.B :: display(); // Calling the display() function defined in B class.
163
6. }
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a()
9. {
10. std::cout << "Enter the value of 'a' : " << std::endl;
11. cin>>a;
12. }
13. };
14.
15. class B : public A
16. {
17. protected:
18. int b;
164
19. public:
20. void get_b()
21. {
22. std::cout << "Enter the value of 'b' : " << std::endl;
23. cin>>b;
24. }
25. };
26. class C
27. {
28. protected:
29. int c;
30. public:
31. void get_c()
32. {
33. std::cout << "Enter the value of c is : " << std::endl;
34. cin>>c;
35. }
36. };
37.
38. class D : public B, public C
39. {
40. protected:
41. int d;
42. public:
43. void mul()
44. {
45. get_a();
46. get_b();
47. get_c();
48. std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
49. }
50. };
51. int main()
52. {
53. D d;
54. d.mul();
55. return 0;
165
56. }
Output:
1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
166
16. }
1. #include <iostream>
2. using namespace std;
3. class Shape // Declaration of base class.
4. {
5. public:
6. int a;
7. int b;
8. void get_data(int n,int m)
9. {
10. a= n;
11. b = m;
12. }
13. };
14. class Rectangle : public Shape // inheriting Shape class
15. {
16. public:
17. int rect_area()
18. {
19. int result = a*b;
20. return result;
21. }
22. };
23. class Triangle : public Shape // inheriting Shape class
24. {
25. public:
26. int triangle_area()
27. {
28. float result = 0.5*a*b;
29. return result;
30. }
31. };
32. int main()
33. {
167
34. Rectangle r;
35. Triangle t;
36. int length,breadth,base,height;
37. std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
38. cin>>length>>breadth;
39. r.get_data(length,breadth);
40. int m = r.rect_area();
41. std::cout << "Area of the rectangle is : " <<m<< std::endl;
42. std::cout << "Enter the base and height of the triangle: " << std::endl;
43. cin>>base>>height;
44. t.get_data(base,height);
45. float n = t.triangle_area();
46. std::cout <<"Area of the triangle is : " << n<<std::endl;
47. return 0;
48. }
Output:
1. #include <iostream>
2. using namespace std;
168
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. {
14. cout<<"Eating bread...";
15. }
16. };
17. int main(void) {
18. Dog d = Dog();
19. d.eat();
20. return 0;
21. }
Output:
Eating bread...
Abstract Class:
By definition, a C++ abstract class must include at least one pure virtual function.
Alternatively, put a function without a definition. Because the subclass would otherwise
turn into an abstract class in and of itself, the abstract class's descendants must specify
the pure virtual function.
Broad notions are expressed using abstract classes, which can then be utilized to
construct more specific classes. You cannot make an object of the abstract class type.
However, pointers and references can be used to abstract class types. When
developing an abstract class, define at least one pure virtual feature. A virtual function
is declared using the pure specifier (= 0) syntax.
169
Consider the example of the virtual function. Although the class's objective is to
provide basic functionality for shapes, elements of type shapes are far too general to
be of much value. Because of this, the shape is a good candidate for an abstract class:
Code
1. C-lass classname //abstract class
2. {
3. //data members
4. public:
5. //pure virtual function
6. /* Other members */
7. };
It is unknown what happens when a pure virtual method is called explicitly or indirectly
by the native code function Object () of an abstract class. Conversely, abstract group
constructors and destructors can call additional member functions.
Although the constructors of the abstract class are allowed to call other member
functions, if they either directly or indirectly call a pure virtual function, the outcome is
unknown. But hold on! What exactly is a pure virtual function?
Let's first examine virtual functions in order to comprehend the pure virtual function.
170
A member function that has been redefined by a derived class from a base class
declaration is referred to as a virtual function.
An interface can only inherit from With the Extended keyword, an abstract
another interface. class can enforce an interface and inherit
from another class.
Use of the implements keyword is Use the extends keyword to inherit from
required in order to implement an an abstract class.
interface.
By creating distinct functions inside the Shape class, you may start with a few basic
forms and hardcode the perimeter.
1. class Shape {
2. public:
3. // All the functions of both square and rectangle are clubbed together in a single class.
4. void width(int w) {
5. shape_width = w;
6. }
7. void height(int h) {
8. shape_height = h;
9. }
10. int areaOfSquare(int s) {
11. return 4 * s;
12. }
13. int areaOfRectange(int l, int b) {
14. return (l * b);
15. }
16. protected:
17. int shape_width;
18. int shape_height;
19. };
20. int main (){
21. shapes R;
22. R.width(5);
23. R.height(10);
24. cout<<"The area of rectangle is"<<R.areaOfRectangle";
25. return 0;
26. }
Output:
172
While OOP advises that we should attempt to adhere to real-world reasoning, this will
still function. As a result, we can create the class Shape as the parent class, with the
classes Square and Rectangle acting as the children. If you want to add something new
later, you can do it in the child class, which will make the program simpler to maintain.
We must use Abstract Classes to put this feature into practice. At least one pure virtual
function is required for abstract classes in C++. In order to prevent the subclass from
becoming an abstract class, the abstract class's inheriting classes must specify the pure
virtual function.
Inheritance Access
// inheritance
#include <iostream>
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
};
public:
};
int main()
PublicDerived object1;
return 0;
Output
Private = 1
Protected = 2
Public = 3
to create getPub() function in the Derived class in order to access the pub
variable.
Example:
C++
// of protected inheritance
#include <iostream>
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
};
176
public:
};
int main()
ProtectedDerived object1;
return 0;
Output
Private cannot be accessed.
Protected = 2
Public = 3
We know that private members cannot be accessed from the Derived class.
These members cannot be directly accessed from outside the class. So we
cannot use getPVT() from PrivateDerived. So we need to create the getPub()
function in PrivateDerived in order to access the pub variable.
Example:
C++
// of private inheritance
#include <iostream>
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
};
public:
};
int main()
PrivateDerived object1;
return 0;
Output
Private cannot be accessed.
Protected = 2
Public = 3
179
In the above diagram, there are two-parent classes: Base Class 1 and Base Class 2,
whereas there is only one Child Class. The Child Class acquires all features from both
Base class 1 and Base class 2. Therefore, we termed the type of Inheritance as Multiple
Inheritance.
10. {
11. // code of the derived class
12. }
In the above syntax, class A and class B are two base classes, and class C is the child
class that inherits some features of the parent classes.
Let's write the various program of Multiple Inheritance to inherit the member functions
and functionality from more than one base class using the derived class.
1. #include <iostream>
2. using namespace std;
3.
4. // create a base class1
5. class Base_class
6. {
7. // access specifier
8. public:
9. // It is a member function
10. void display()
11. {
12. cout << " It is the first function of the Base class " << endl;
13. }
14. };
15.
16. // create a base class2
17. class Base_class2
18. {
19. // access specifier
20. public:
21. // It is a member function
22. void display2()
23. {
24. cout << " It is the second function of the Base class " << endl;
25. }
181
26. };
27.
28. /* create a child_class to inherit features of Base_class and Base_class2 with access specifier. *
/
29. class child_class: public Base_class, public Base_class2
30. {
31.
32. // access specifier
33. public:
34. void display3() // It is a member function of derive class
35. {
36. cout << " It is the function of the derived class " << endl;
37. }
38.
39. };
40.
41. int main ()
42. {
43. // create an object for derived class
44. child_class ch;
45. ch.display(); // call member function of Base_class1
46. ch.display2(); // call member function of Base_class2
47. ch.display3(); // call member function of child_class
48. }
Output
In the above program, we created two base classes and one child class.
The child_class invoke member function display() and display2() from both parent
classes Base_class and Base_class2 with the help of child class's object ch.
Program2.cpp
1. #include <iostream>
2. using namespace std;
3.
4. // create add class
5. class add
6. {
7. public:
8. int x = 20;
9. int y = 30;
10. void sum()
11. {
12. cout << " The sum of " << x << " and " << y << " is " <<x+y << endl;
13. }
14. };
15.
16. // create Mul class
17. class Mul
18. {
19. public:
20. int a = 20;
21. int b = 30;
22. void mul()
23. {
24. cout << " The Multiplication of " << a << " and " << b << " is " <<a*b << endl;
25. }
26. };
27.
28. // create Subclass
29. class Sub
30. {
31. public:
32. int a = 50;
33. int b = 30;
34. void sub()
35. {
183
36. cout << " The Subtraction of " << a << " and " << b << " is " <<a-b << endl;
37. }
38. };
39.
40. // create Div class
41. class Div
42. {
43. // access specifier
44. public:
45. int a = 150;
46. int b = 30;
47. void div()
48. {
49. cout << " The Division of " << a << " and " << b << " is " <<a/b << endl;
50. }
51. };
52.
53. // create a derived class to derive the member functions of all base classes
54. class derived: public add, public Div, public Sub, public Mul
55. {
56. // access specifier
57. public:
58. int p = 12;
59. int q = 5;
60. void mod()
61. {
62. cout << "The Modulus of " << p << " and " <<q << " is " << p % q << endl;
63. }
64. };
65.
66. int main ()
67. {
68. // create an object of the derived class
69. derived dr;
70. dr.mod(); // call derive class member function
71. // call all member function of class add, Div, Sub and Mul
72. dr.sum();
184
73. dr.mul();
74. dr.div();
75. dr.sub();
76. }
Output
Program3.cpp
1. #include <iostream>
2. using namespace std;
3.
4. // create base class1
5. class student_detail
6. {
7. // access specifier
8. protected:
9. int rno, sum = 0, i, marks[5];
10.
11. // access specifier
12. public:
13. void detail()
14. {
15.
16.
17. cout << " Enter the Roll No: " << endl;
18. cin >> rno;
19.
20. cout << " Enter the marks of five subjects " << endl;
185
57.
58. // create member function of child class
59. void disp ()
60. {
61. tot = sum + s_mark;
62. avg = tot / 6; // total marks of six subject / 6
63. cout << " \n \n \t Roll No: " << rno << " \n \t Total: " << tot << endl;
64. cout << " \n \t Average Marks: " << avg;
65. }
66. };
67.
68. int main ()
69. {
70. result obj; // create an object of the derived class
71.
72. // call the member function of the base class
73. obj.detail();
74. obj.get_mark();
75. obj.disp();
76. }
Output
Roll No: 25
Total: 527
Average Marks: 87
Ambiguity Problem in Multiple Inheritance
In Multiple Inheritance, when a single class is derived from two or more base or parent
classes. So, it might be possible that both the parent class have the same-named
member functions, and it shows ambiguity when the child class object invokes one of
187
the same-named member functions. Hence, we can say, the C++ compiler is confused
in selecting the member function of a class for the execution of a program.
Program4.cpp
1. #include <iostream>
2. #include <conio.h>
3.
4. using namespace std;
5.
6. // create class A
7. class A
8. {
9. public:
10. void show()
11. {
12. cout << " It is the member function of class A " << endl;
13. }
14. };
15.
16. // create class B
17. class B
18. {
19. public:
20. void show()
21. {
22. cout << " It is the member function of class B " << endl;
23. }
24. };
25.
26.
27. // create a child class to inherit the member function of class A and class B
28. class child: public A, public B
188
29. {
30. public:
31. void disp()
32. {
33. cout << " It is the member function of the child class " << endl;
34. }
35. };
36.
37. int main ()
38. {
39. // create an object of the child class to access the member function
40. child ch;
41. ch.show(); // It causes ambiguity
42. ch.disp();
43. return 0;
44. }
When the above program is compiled, it throws the show() member function is
ambiguous. Because of both the base class A and B, defining the same member
function show(), and when the derived class's object call the shows() function, it shows
ambiguity in multiple inheritances.
For example,
1. ch.A:: show(); // class_name and scope resolution operator with member function
2. ch.B::show();
After making some changes, now we again execute the above program that returns
the given below Output.
Virtual Function:
o A C++ virtual function is a member function in the base class that you redefine
in a derived class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the
function.
o There is a necessity to use the single pointer to refer to all the objects of the
different classes. So, we create the pointer to the base class that refers to all the
derived objects. But, when base class pointer contains the address of the
derived class object, always executes the base class function. This issue can only
be resolved by using the 'virtual' function.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o When the function is made virtual, C++ determines which function is to be
invoked at the runtime based on the type of the object pointed by the base
class pointer.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int x=5;
6. public:
7. void display()
8. {
9. std::cout << "Value of x is : " << x<<std::endl;
10. }
11. };
12. class B: public A
13. {
14. int y = 10;
15. public:
16. void display()
17. {
18. std::cout << "Value of y is : " <<y<< std::endl;
19. }
20. };
21. int main()
22. {
23. A *a;
24. B b;
25. a = &b;
26. a->display();
27. return 0;
28. }
Output:
Value of x is : 5
In the above example, * a is the base class pointer. The pointer can only access the
base class members but not the members of the derived class. Although C++ permits
the base pointer to point to any object derived from the base class, it cannot directly
191
access the members of the derived class. Therefore, there is a need for virtual function
which allows the base pointer to access the members of the derived class.
1. #include <iostream>
2. {
3. public:
4. virtual void display()
5. {
6. cout << "Base class is invoked"<<endl;
7. }
8. };
9. class B:public A
10. {
11. public:
12. void display()
13. {
14. cout << "Derived Class is invoked"<<endl;
15. }
16. };
17. int main()
18. {
19. A* a; //pointer of base class
20. B b; //object of derived class
21. a = &b;
22. a->display(); //Late Binding occurs
23. }
Output:
o A virtual function is not used for performing any task. It only serves as a
placeholder.
o When the function has no definition, such function is known as "do-nothing"
function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual
function is a function declared in the base class that has no definition relative
to the base class.
o A class containing the pure virtual function cannot be used to declare the
objects of its own, such classes are known as abstract base classes.
o The main objective of the base class is to provide the traits to the derived classes
and to create the base pointer used for achieving the runtime polymorphism.
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void show() = 0;
7. };
8. class Derived : public Base
9. {
10. public:
11. void show()
12. {
13. std::cout << "Derived class is derived from the base class." << std::endl;
14. }
15. };
16. int main()
17. {
18. Base *bptr;
19. //Base b;
193
20. Derived d;
21. bptr = &d;
22. bptr->show();
23. return 0;
24. }
Output:
In the above example, the base class contains the pure virtual function. Therefore, the
base class is an abstract base class. We cannot create the object of the base class.
Friend Function:
If a function is defined as a friend function in C++, then the protected and private data
of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the
body of a class starting with the keyword friend.
In the above declaration, the friend function is preceded by the keyword friend. The
function can be defined anywhere in the program like a normal C++ function. The
function definition does not use either the keyword friend or scope resolution
operator.
o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
194
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }
Output:
Length of box: 10
Let's see a simple example when the function is friendly to two classes.
1. #include <iostream>
2. using namespace std;
3. class B; // forward declarartion.
195
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i)
9. {
10. x=i;
11. }
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }
196
Output:
10
In the above example, min() function is friendly to two classes, i.e., the min() function
can access the private members of both the classes A and B.
1. #include <iostream>
2.
3. using namespace std;
4.
5. class A
6. {
7. int x =5;
8. friend class B; // friend class.
9. };
10. class B
11. {
12. public:
13. void display(A &a)
14. {
15. cout<<"value of x is : "<<a.x;
16. }
17. };
18. int main()
19. {
20. A a;
21. B b;
22. b.display(a);
23. return 0;
24. }
Output:
197
value of x is : 5
In the above example, class B is declared as a friend inside the class A. Therefore, B is
a friend of class A. Class B can access the private members of class A.
Static Function:
The static is a keyword in the C and C++ programming language. We use the static
keyword to define the static data member or static member function inside and outside
of the class. Let's understand the static data member and static member function using
the programs.
Syntax
The data_type is the variable type in C++, such as int, float, string, etc.
Example 1: Let's create a simple program to access the static data members in the
C++ programming language.
1. #include <iostream>
2. #include <string.h>
3. using namespace std;
4. // create class of the Car
5. class Car
6. {
7. private:
8. int car_id;
9. char car_name[20];
10. int marks;
11.
12. public:
13. // declare a static data member
14. static int static_member;
15.
16. Car()
17. {
18. static_member++;
19. }
20.
21. void inp()
22. {
23. cout << " \n\n Enter the Id of the Car: " << endl;
24. cin >> car_id; // input the id
25. cout << " Enter the name of the Car: " << endl;
26. cin >> car_name;
27. cout << " Number of the Marks (1 - 10): " << endl;
28. cin >> marks;
29. }
30.
31. // display the entered details
32. void disp ()
33. {
34. cout << " \n Id of the Car: " << car_id;
199
35. cout << "\n Name of the Car: " << car_name;
36. cout << " \n Marks: " << marks;
37.
38. }
39. };
40.
41. // initialized the static data member to 0
42. int Car::static_member = 0;
43.
44. int main ()
45. {
46. // create object for the class Car
47. Car c1;
48. // call inp() function to insert values
49. c1. inp ();
50. c1. disp();
51.
52. //create another object
53. Car c2;
54. // call inp() function to insert values
55. c2. inp ();
56. c2. disp();
57.
58.
59. cout << " \n No. of objects created in the class: " << Car :: static_member <<endl;
60. return 0;
61. }
Output
Syntax
1. class_name::function_name (parameter);
function_name: The function name is the name of the static member function.
parameter: It defines the name of the pass arguments to the static member function.
Example 2: Let's create another program to access the static member function using
the class name in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
6. static int num;
7.
8. public:
9. // create static member function
10. static int func ()
11. {
12. return num;
13. }
201
14. };
15. // initialize the static data member using the class name and the scope resolution operator
16. int Note :: num = 5;
17.
18. int main ()
19. {
20. // access static member function using the class name and the scope resolution
21. cout << " The value of the num is: " << Note:: func () << endl;
22. return 0;
23. }
Output
Example 3: Let's create another program to access the static member function using
the class' object in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
6. static int num;
7.
8. public:
9. // create static member function
10. static int func ()
11. {
12. cout << " The value of the num is: " << num << endl;
13. }
14. };
15. // initialize the static data member using the class name and the scope resolution operator
16. int Note :: num = 15;
17.
18. int main ()
19. {
20. // create an object of the class Note
21. Note n;
202
Output
Example 4: Let's consider an example to access the static member function using the
object and class in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3. class Member
4. {
5.
6. private:
7. // declaration of the static data members
8. static int A;
9. static int B;
10. static int C;
11.
12. // declare public access specifier
13. public:
14. // define the static member function
15. static void disp ()
16. {
17. cout << " The value of the A is: " << A << endl;
18. cout << " The value of the B is: " << B << endl;
19. cout << " The value of the C is: " << C << endl;
20. }
21. };
22. // initialization of the static data members
23. int Member :: A = 20;
24. int Member :: B = 30;
25. int Member :: C = 40;
26.
203
Output
SECTION-IV
EXCEPTION HANDLING
Various methods to handle exception handling and base and derived class catch as
part of exception in both C++ and Java programming languages.
o In a scenario where the base and the derived classes we have declared are caught in
the mechanism as exceptions, then we must see at the display output terminal that the
catch block of the said derived class appears before the type of base we declared.
o The above statement is valid, and we can even recheck if we put our base class before
the derived class, then the derived class which we have declared will never be reached.
C++ Code
205
Output:
C++ code
206
Output:
Java Code
5. }
6. class derived_ extends base_ {
7. }
8. public class Main{
9. public static void main(String args[])
10. {
11. try {
12. throw new derived_();
13. }
14. catch (base_ b) {
15. }
16. catch (derived_ d) {
17. }
18. }
19. }
Output:
Java Code
15. }
16. catch(derived_d) {
17. System.out.println("the code has been caught in the derived exception");
18. }
19. }
20. }
Output:
C++ Exceptions:
When executing C++ code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error
message. The technical term for this is: C++ will throw an exception (error).
C++ try and catch:
Exception handling in C++ consists of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
The throw keyword throws an exception when a problem is detected, which
lets us create a custom error.
The catch statement allows you to define a block of code to be executed if
an error occurs in the try block.
The try and catch keywords come in pairs:
We use the try block to test some code: If the value of a variable “age” is less
than 18, we will throw an exception, and handle it in our catch block.
In the catch block, we catch the error if it occurs and do something about it.
The catch statement takes a single parameter. So, if the value of age is 15
and that’s why we are throwing an exception of type int in the try block (age),
we can pass “int myNum” as the parameter to the catch statement, where
the variable “myNum” is used to output the value of age.
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater
than 18), the catch block is skipped.
Exception Handling in C++
1) The following is a simple example to show exception handling in C++. The
output of the program explains the flow of execution of try/catch blocks.
CPP
#include <iostream>
int main()
int x = -1;
// Some code
try {
if (x < 0)
throw x;
catch (int x ) {
return 0;
Output:
211
Before try
Inside try
Exception Caught
After catch (Will be executed)
2) There is a special catch block called the ‘catch all’ block, written as
catch(…), that can be used to catch all types of exceptions. For example, in
the following program, an int is thrown as an exception, but there is no catch
block for int, so the catch(…) block will be executed.
CPP
#include <iostream>
int main()
try {
throw 10;
catch (...) {
return 0;
212
Output:
Default Exception
3) Implicit type conversion doesn’t happen for primitive types. For example,
in the following program, ‘a’ is not implicitly converted to int.
CPP
#include <iostream>
int main()
try {
throw 'a';
catch (int x) {
catch (...) {
return 0;
}
213
Output:
Default Exception
4) If an exception is thrown and not caught anywhere, the program
terminates abnormally. For example, in the following program, a char is
thrown, but there is no catch block to catch the char.
CPP
#include <iostream>
int main()
try {
throw 'a';
catch (int x) {
return 0;
Output:
terminate called after throwing an instance of 'char'
#include <iostream>
// Ideally, the function should specify all uncaught exceptions and function
if (ptr == NULL)
throw ptr;
if (x == 0)
throw x;
/* Some functionality */
215
int main()
try {
fun(NULL, 0);
catch(...) {
return 0;
Output:
Caught exception from fun()
A better way to write the above code:
CPP
#include <iostream>
// throws.
216
void fun(int *ptr, int x) throw (int *, int) // Dynamic Exception specification
if (ptr == NULL)
throw ptr;
if (x == 0)
throw x;
/* Some functionality */
int main()
try {
fun(NULL, 0);
catch(...) {
return 0;
will abort itself because in that scenario, it calls (indirectly) terminate(), which
by default calls abort().
Output:
Caught exception from fun()
8) In C++, try/catch blocks can be nested. Also, an exception can be re-
thrown using “throw; “.
CPP
#include <iostream>
int main()
try {
try {
throw 20;
catch (int n) {
catch (int n) {
}
218
return 0;
Output:
Handle Partially Handle remaining
A function can also re-throw a function using the same “throw; ” syntax. A
function can handle a part and ask the caller to handle the remaining.
9) When an exception is thrown, all objects created inside the enclosing try
block are destroyed before the control is transferred to the catch block.
CPP
#include <iostream>
class Test {
public:
};
int main()
try {
Test t1;
throw 10;
219
catch (int i) {
Output:
Constructor of Test
Destructor of Test
Caught 10
Unexpected Exception:
Whenever an exception arises in C++, it is handled as per the behavior
defined using the try-catch block. However, there is often the case when an
exception is thrown but isn’t caught because the exception handling
subsystem fails to find a matching catch block for that particular exception. In
that case, the following set of actions takes place:
1. The exception handling subsystem calls the function: unexpected(). This
function, provided by the default C++ library, defines the behavior when
an uncaught exception arises. By default, unexpected calls terminate().
2. The terminate function defines the actions that are to be performed during
process termination. This, by default, calls abort().
3. The process is aborted.
The terminate() and unexpected() simply call other functions to actually
handle an error. As explained above, terminate calls abort(), and
unexpected() calls terminate(). Thus, both functions halt the program
execution when an exception handling error occurs. However, you can
change the way termination occurs.
To change the terminate handler, the function used is
set_terminate(terminate_handler newhandler), which is defined in the
header <exception>.
The following program demonstrates how to set a custom termination
handler:
220
#include <exception>
#include <iostream>
void myhandler()
abort();
int main()
set_terminate(myhandler);
try {
throw 100;
}
221
return 0;
Output:
Inside try block
Inside new terminate handler
Runtime Error:
Abort signal from abort(3) (SIGABRT)
It is to be duly noted that the only thing that your custom terminate handler
must do is stop the program execution. It must not return to the program or
resume it in any way.
In C++, exception is an event or object which is thrown at runtime. All exceptions are
derived from std::exception class. It is a runtime error which can be handled. If we don't
handle the exception, it prints exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is
executed even after exception.
In C++ standard exceptions are defined in <exception> class that we can use inside
our programs. The arrangement of parent-child class hierarchy is shown below:
All the exception classes in C++ are derived from std::exception class. Let's see the list
of C++ common exception classes.
Exception Description
o try
o catch, and
o throw
//: C01:Rawp.cpp
// Naked pointers.
#include
#include
using namespace std;
class Cat {
public:
Cat() { cout << "Cat()" << endl; }
~Cat() { cout << "~Cat()" << endl; }
};
class Dog {
public:
void* operator new(size_t sz) {
224
class UseResources {
Cat* bp;
Dog* op;
public:
UseResources(int count = 1) {
cout << "UseResources()" << endl;
bp = new Cat[count];
op = new Dog;
}
~UseResources() {
cout << "~UseResources()" << endl;
delete [] bp; // Array delete
delete op;
}
};
int main() {
try {
UseResources ur(3);
} catch(int) {
cout << "inside handler" << endl;
}
} ///:~
The output is
UseResources()
Cat()
Cat()
Cat()
allocating a Dog
inside handler
The UseResources constructor is entered, and the Cat constructor is successfully
completed for the three array objects. However, inside Dog::operator new( ), an
exception is thrown (to simulate an out-of-memory error). Suddenly, you end up inside
the handler, without the UseResources destructor being called. This is correct because
the UseResources constructor was unable to finish, but it also means the Cat objects
that were successfully created on the heap were never destroyed.
225
Template Classes:
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming.
Generic programming is a technique where generic types are used as parameters in
algorithms so that they can work for a variety of data types.
o Function templates
o Class templates
Function Templates:
We can define a template for a function. For example, if we have an add() function, we
can create versions of the add function for adding the int, float or double type values.
Class Template:
We can define a template for a class. For example, a class template can be created for
the array class that can accept the array of various types such as int array, float array
or double array.
Function Template
o Generic functions use the concept of a function template. Generic functions define a
set of operations that can be applied to the various types of data.
226
o The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
o For example, Quick sorting algorithm is implemented using a generic function, it can
be implemented to an array of integers or array of floats.
o A Generic function is created by using the keyword template. The template defines
what function will do.
Where Ttype: It is a placeholder name for a data type used by the function. It is used
within the function definition. It is only a placeholder that the compiler will
automatically replace this placeholder with the actual data type.
1. #include <iostream>
2. using namespace std;
3. template<class T> T add(T &a,T &b)
4. {
5. T result = a+b;
6. return result;
7.
8. }
9. int main()
10. {
11. int i =2;
12. int j =3;
13. float m = 2.3;
14. float n = 1.2;
15. cout<<"Addition of i and j is :"<<add(i,j);
16. cout<<'\n';
17. cout<<"Addition of m and n is :"<<add(m,n);
227
18. return 0;
19. }
Output:
Addition of i and j is :5
Addition of m and n is :3.5
In the above example, we create the function template which can perform the addition
operation on any type either it can be integer, float or double.
Syntax
In the above syntax, we have seen that the template function can accept any number
of arguments of a different type.
1. #include <iostream>
2. using namespace std;
3. template<class X,class Y> void fun(X a,Y b)
4. {
5. std::cout << "Value of a is : " <<a<< std::endl;
6. std::cout << "Value of b is : " <<b<< std::endl;
7. }
8.
9. int main()
10. {
11. fun(15,12.3);
12.
228
13. return 0;
14. }
Output:
Value of a is : 15
Value of b is : 12.3
In the above example, we use two generic types in the template function, i.e., X and Y.
1. #include <iostream>
2. using namespace std;
3. template<class X> void fun(X a)
4. {
5. std::cout << "Value of a is : " <<a<< std::endl;
6. }
7. template<class X,class Y> void fun(X b ,Y c)
8. {
9. std::cout << "Value of b is : " <<b<< std::endl;
10. std::cout << "Value of c is : " <<c<< std::endl;
11. }
12. int main()
13. {
14. fun(10);
15. fun(20,30.5);
16. return 0;
17. }
Output:
Value of a is : 10
Value of b is : 20
Value of c is : 30.5
1. #include <iostream>
2. using namespace std;
3. void fun(double a)
4. {
5. cout<<"value of a is : "<<a<<'\n';
6. }
7.
8. void fun(int b)
9. {
10. if(b%2==0)
11. {
12. cout<<"Number is even";
13. }
14. else
15. {
16. cout<<"Number is odd";
17. }
18.
19. }
20.
21. int main()
22. {
23. fun(4.6);
24. fun(6);
25. return 0;
26. }
Output:
value of a is : 4.6
Number is even
230
In the above example, we overload the ordinary functions. We cannot overload the
generic functions as both the functions have different functionalities. First one is
displaying the value and the second one determines whether the number is even or
not.
CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a class
uses the concept of Template, then the class is known as generic class.
Syntax
1. template<class Ttype>
2. class class_name
3. {
4. .
5. .
6. }
Ttype is a placeholder name which will be determined when the class is instantiated.
We can define more than one generic data type using a comma-separated list. The
Ttype can be used inside the class body.
1. class_name<type> ob;
type: It is the type of the data that the class is operating on.
1. #include <iostream>
2. using namespace std;
3. template<class T>
4. class A
5. {
231
6. public:
7. T num1 = 5;
8. T num2 = 6;
9. void add()
10. {
11. std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
12. }
13.
14. };
15.
16. int main()
17. {
18. A<int> d;
19. d.add();
20. return 0;
21. }
Output:
In the above example, we create a template for class A. Inside the main() method, we
create the instance of class A named as, 'd'.
Syntax
Let's see a simple example when class template contains two generic data types.
1. #include <iostream>
232
Output:
5. };
In the above case, the nontype template argument is size and therefore, template
supplies the size of the array as an argument.
1. #include <iostream>
2. using namespace std;
3. template<class T, int size>
4. class A
5. {
6. public:
7. T arr[size];
8. void insert()
9. {
10. int i =1;
11. for (int j=0;j<size;j++)
12. {
13. arr[j] = i;
14. i++;
15. }
16. }
17.
18. void display()
19. {
20. for(int i=0;i<size;i++)
21. {
22. std::cout << arr[i] << " ";
23. }
24. }
25. };
26. int main()
234
27. {
28. A<int,10> t1;
29. t1.insert();
30. t1.display();
31. return 0;
32. }
Output:
1 2 3 4 5 6 7 8 9 10
In the above example, the class template is created which contains the nontype
template argument, i.e., size. It is specified when the object of class 'A' is created.
Points to Remember
Namespace String:
Namespace provide the space where we can define or declare identifier
i.e. variable, method, classes.
Using namespace, you can define the space or context in which
identifiers are defined i.e. variable, method, classes. In essence, a
namespace defines a scope.
Example, you might be writing some code that has a function called xyz()
and there is another library available which is also having same function
xyz(). Now the compiler has no way of knowing which version of xyz()
function you are referring to within your code.
235
Defining a Namespace:
You can also avoid prepending of namespaces with the using namespace
directive. This directive tells the compiler that the subsequent code is
making use of names in the specified namespace.
The namespace is thus implied for the following code:
C++
#include <iostream>
namespace first_space
236
void func()
namespace second_space
void func()
int main ()
func();
return 0;
237
Output
Inside first_space
Names introduced in a using directive obey normal scope rules. The
name is visible from the point of the using directive to the end of the
scope in which the directive is found. Entities with the same name defined
in an outer scope are hidden.
Nested Namespaces:
Namespaces can be nested where you can define one namespace inside
another name space as follows:
SYNTAX:
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}
You can access members of nested namespace by using resolution
operators as follows:
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace_name1
using namespace namespace_name1;
C++
#include <iostream>
238
namespace first_space
void func()
namespace second_space
void func()
int main ()
{
239
func();
return 0;
Output
Inside second_space
Let us see how namespace scope the entities including variable and
functions:
C++
#include <iostream>
namespace first_space
void func()
namespace second_space
240
void func()
int main ()
first_space :: func();
second_space :: func();
return 0;
Output
Inside first_space
Inside second_space
Consider the following C++ program:
CPP
int main()
int value;
value = 0;
value = 0.0;
Output :
Compiler Error:
'value' has a previous declaration as 'int value'
In each scope, a name can only represent one entity. So, there cannot be
two variables with the same name in the same scope. Using namespaces,
we can create two variables or member functions having the same name.
CPP
#include <iostream>
namespace first {
// Global variable
int main()
// Local variable
// operator ::
return 0;
Output
500
Definition and Creation: Namespaces allow us to group named entities that
otherwise would have global scope into narrower scopes, giving
243
C++
namespace namespace_name{
}
244
C++
// Let us see how namespace scope the entities including variable and functions:
#include <iostream>
namespace first_space
void func()
namespace second_space
{
245
void func()
int main ()
first_space::func();
second_space::func();
return 0;
// If we compile and run above code, this would produce the following result:
// Inside first_space
// Inside second_space
Output
Inside first_space
Inside second_space
The using directive:
You can avoid prepending of namespaces with the using namespace
directive. This directive tells the compiler that the subsequent code is making
246
C++
#include <iostream>
namespace first_space
void func()
namespace second_space
void func()
int main ()
func();
return 0;
// If we compile and run above code, this would produce the following result:
// Inside first_space
Output
Inside first_space
Instead of accessing the whole namespace, another option (known
as using declaration) is to access a particular item within a namespace. For
example, if the only part of the std namespace that you intend to use is cout,
you can refer to it as follows:
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but
other items in the std namespace will still need to be explicit as follows:
C++
248
#include <iostream>
using std::cout;
int main ()
return 0;
Output
std::endl is used with std!
Names introduced in a using directive obey normal scope rules, i.e., they are
visible from the point the using directive occurs to the end of the scope in
which the directive is found. Entities with the same name defined in an outer
scope are hidden.
C++
// Creating namespaces
#include <iostream>
namespace ns1 {
} // namespace ns1
namespace ns2 {
249
} // namespace ns2
int main()
return 0;
Output:
5
200
100
Classes and Namespace: The following is a simple way to create classes in
a namespace:
250
C++
// in a namespace
#include<iostream>
namespace ns
// A Class in a namespace
class geek
public:
void display()
cout<<"ns::geek::display()"<<endl;;
};
int main()
{
251
ns::geek obj;
obj.display();
return 0;
Output
ns::geek::display()
A class can also be declared inside namespace and defined outside
namespace using the following syntax:
CPP
// in a namespace
#include <iostream>
namespace ns {
class geek;
} // namespace ns
252
class ns::geek {
public:
};
int main()
ns::geek obj;
obj.display();
return 0;
Output
ns::geek::display()
We can define methods as well outside the namespace. The following is
an example code:
C++
#include <iostream>
// Creating a namespace
namespace ns {
void display();
class geek {
public:
void display();
};
} // namespace ns
void ns::geek::display()
// Driver code
int main()
ns::geek obj;
254
ns::display();
obj.display();
return 0;
Output:
ns::display()
ns::geek::display():
Nested Namespaces:
Namespaces can be nested, i.e., you can define one namespace inside
another namespace as follows:
C++
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
You can access the members of a nested namespace by using the resolution
operator (::) as follows:
C++
255
C++
#include <iostream>
namespace first_space
void func()
namespace second_space
{
256
void func()
int main ()
func();
return 0;
// If we compile and run above code, this would produce the following result:
// Inside second_space
Output
Inside second_space
Namespace provides the advantage of avoiding name collision:-
For example, you might be writing some code that has a function called xyz()
and there is another library available in your code which also has the same
function xyz(). Now the compiler has no way of knowing which version of
257
Iterators:
Iterators are just like pointers used to access the container elements.
Important Points:
o Iterators are used to traverse from one element to another element, a process is known
as iterating through the container.
o The main advantage of an iterator is to provide a common interface for all the
containers type.
o Iterators make the algorithm independent of the type of the container used.
o Iterators provide a generic approach to navigate through the elements of a container.
Syntax
1. <ContainerType> :: iterator;
2. <ContainerType> :: const_iterator;
Iterators can be smart pointers which allow to iterate over the complex data structures.
A Container provides its iterator type. Therefore, we can say that the iterators have the
common interface with different container type.
The container classes provide two basic member functions that allow to iterate or
move through the elements of a container:
o begin(): The begin() function returns an iterator pointing to the first element of the
container.
o end(): The end() function returns an iterator pointing to the past-the-last element of
the container.
1. #include <iostream>
2. #include<iterator>
3. #include<vector>
4. using namespace std;
5. int main()
6. {
7. std::vector<int> v{1,2,3,4,5};
8. vector<int>::iterator itr;
9. for(itr=v.begin();itr!=v.end();itr++)
10. {
11. std::cout << *itr <<" ";
12. }
13. return 0;
14. }
Output:
1 2 3 4 5
259
Iterator Categories
An iterator can be categorized in the following ways:
o Input Iterator
o Output Iterator
o Forward Iterator
o Bidirectional Iterator
o Random Access Iterator
Input Iterator: An input iterator is an iterator used to access the elements from the
container, but it does not modify the value of a container.
o Increment operator(++)
o Equal operator(==)
o Not equal operator(!=)
o Dereference operator(*)
o Increment operator(++)
o Assignment operator(=)
260
Forward Iterator: A forward iterator is an iterator used to read and write to a container.
It is a multi-pass iterator.
o Increment operator(++)
o Assignment operator(=)
o Equal operator(=)
o Not equal operator(!=)
o Increment operator(++)
o Assignment operator(=)
o Equal operator(=)
o Not equal operator(!=)
o Decrement operator(--)
Providers Of Iterators
Forward iterator
Disadvantages of iterator
o If we want to move from one data structure to another at the same time, iterators won't
work.
o If we want to update the structure which is being iterated, an iterator won?t allow us
to do because of the way it stores the position.
o If we want to backtrack while processing through a list, the iterator will not work in this
case.
Advantages of iterator
Following are the advantages of an iterator:
1. #include <iostream>
2. #include<vector>
3. #include<iterator>
4. using namespace std;
5. int main()
6. {
7. vector<int> v{1,2,3,4,5};
8. vector<int>::iterator itr;
9. for(int i=0;i<5;i++) // Traversal without using an iterator.
10. {
11. cout<<v[i]<<" ";
12. }
13. cout<<'\n';
14. for(itr=v.begin();itr!=v.end();itr++) // Traversal by using an iterator.
15. {
16. cout<<*itr<<" ";
17. }
18. v.push_back(10);
19. cout<<'\n';
20. for(int i=0;i<6;i++)
21. {
22. cout<<v[i]<<" ";
23. }
24. cout<<'\n';
25. for(itr=v.begin();itr!=v.end();itr++)
26. {
27. cout<<*itr<<" ";
28. }
29. return 0;
30. }
Output:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5 10
1 2 3 4 5 10
263
In the above example, we observe that if we traverse the elements of a vector without
using an iterator, then we need to keep track of the number of elements added in the
container.
o Code Reusability: A code can be reused if we use iterators. In the above example, if we
replace vector with the list, and then the subscript operator[] would not work to access
the elements as the list does not support the random access. However, we use iterators
to access the elements, then we can also access the list elements.
o Dynamic Processing: C++ iterators provide the facility to add or delete the data
dynamically.
1. #include <iostream>
2. #include<vector>
3. #include<iterator>
4. using namespace std;
5. int main()
6. {
7. vector<int> v{1,2,3,4,5}; // vector declaration
8. vector<int>::iterator itr;
9. v.insert(v.begin()+1,10);
10. for(itr=v.begin();itr!=v.end();itr++)
11. {
12. cout<<*itr<<" ";
13. }
14. return 0;
15. }
Output:
1 10 2 3 4 5
In the above example, we insert a new element at the second position by using insert()
function and all other elements are shifted by one.
The most important difference between the Random access iterator and other iterators
is that random access iterator requires '1' step to access an element while other iterators
require 'n' steps.
Hashes:
The hash class is default constructible, which means that one can construct
this object without any arguments or initialization values. It is used to get the
hash value of the argument that is being passed to it. If the argument doesn’t
change, the value doesn’t change either.
Syntax:
Member functions: This Hash class only has one member function:
CPP
#include <bitset>
// functional header
#include <functional>
#include <iostream>
#include <string>
#include <vector>
void stringHashing()
// Instantiation of Object
hash<string> mystdhash;
<< mystdhash(hashing1)
<< endl;
void bitsetHashing()
bitset<5> h_bitset("10101");
// Instantiation of Object
267
void vectorHashing()
vector<bool>
true, false };
// Instantiation of Object
<< hash_vector_bool(h_vecbool)
<< endl;
void charHashing()
char ch = 'a';
// Instantiation of Object
hash<char> hash_char;
<< hash_char(ch)
<< endl;
}
269
// Driver Code
int main()
stringHashing();
bitsetHashing();
vectorHashing();
charHashing();
Output:
String hash values: 4457761756728957899
1. #include <iostream.h>
2. #include "iostream.h"
1. Input Stream: To take any input from the user, we need to use cin, which belongs to
the input stream
1. std::cin>>variable_name
When the cin is executed, the cursor will be stopped at the particular statement until
the value is entered. The value entered will be stored in a variable.
2. Output Stream: To print the output, we use built-in functions in the cout output
stream
1. std::cout<<variable_name
Using cin, we can take input from the user and store the value in the variable. We need
to use the cin keyword followed by >> and the variable name.
Syntax:
1. std::cin>>variable_name
To use cin, we need to use #include <iostream.h> as cin belongs to this header file, and
without this, an error will occur.
5. {
6. string name;
7. //cin declaration
8. cin >> name;
9. return 0;
10. }
Output:
Explanation:
In the above code, we used cin to take the input, so to use cin, we included
<iostream.h> header file. When the input is taken, the string input is stored in the
name variable.
2. Cout
To print the output, we need to use the cout keyword, which belongs to the iostream
header file. To use cout, we need to use the cout keyword followed by << and variable
or the statement to print the output.
1. std::cout<<variable_name
1. //to use the cout statement, we need to use the iostream header file
2. #include <iostream.h>
3. using namespace std;
4. int main()
5. {
6. //cout statement is used here to print the statement
7. cout << "Hi from cout statement";
272
8. return 0;}
Output:
Explanation:
In the above code, we used a cout statement to print the statement. To use the cout
statement, we need to include iostream.h header file. Once the cout is executed,
statement or variable value will be printing the output. To print any statement, we need
to use double quotes (" "), and to print a variable value; we need to use just the variable
name without double quotes(" ")
3. Cerr
Cerr is used to print errors in C++, which is present in the iostream header file. If we
need to print any error message in the code if any condition fails, then cerr is very
helpful.
1. cerr<<variable_name
Example:
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int a;
5. cin>>a;
6. if(a%2==0){
7. cout<<"The number entered in even number"<<endl;
8. }
273
9. else{
10. std::cerr << "Enter proper number" << '\n';
11. }
12. return 0;
13. }
Output:
Explanation:
In the above example, we used cin to take the input and check if the given number is
even or not. If the given number is not even, we need to print an error that the given
number is not an even number. We use the cerr keyword in the iostream header file to
print this error.
4. Clog:
The clog is also used to print error messages, but unlike cerr, clog is buffered, which
means the error message is stored in a buffer and then will be printed, but cerr is
unbuffered and will not store the error message in the buffer. The clog also belongs
to the iostream header file. As the clog is buffered, it will not show the error message
immediately. The clog is preferred more than cerr when efficiency is more important.
1. clog<<variable_name;
Example:
1. #include <iostream>
2. using namespace std;
3.
4.
274
5. int main()
6. {
7. clog << "This message is stored in the buffer";
8. return 0;
9. }
Output:
Explanation:
In the above code, we are printing an error. To print this error, we use cerr, which
belongs to the iostream header file. Before printing the error, we store the error in a
buffer.
1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. int a;
7. string b;
8. cin>>a;
9.
10. if(a%2==0){
11. cout<<"The number entered is even number enter a name"<<endl;
12. cin>>b;
13. cout<<b;
14. }
275
15. else{
16. std::cerr << "Enter even number" << '\n';
17.
18.
19. }
20.
21. }
Output:
Explanation: In the above code, we used all the input and output streams in the
iostream.h header file.