Dheeraj Malhotra, Neha Malhotra - C++ Programming Fundamentals-Mercury Learning and Information (2023)
Dheeraj Malhotra, Neha Malhotra - C++ Programming Fundamentals-Mercury Learning and Information (2023)
Fundamentals
LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY
By purchasing or using this book and disc (the “Work”), you agree that this
license grants permission to use the contents contained herein, including the
disc, but does not give you the right of ownership to any of the textual content in
the book / disc or ownership to any of the information or products contained in
it. This license does not permit uploading of the Work onto the Internet or on a
network (of any kind) without the written consent of the Publisher. Duplication
or dissemination of any text, code, simulations, images, etc. contained herein
is limited to and subject to licensing terms for the respective products, and
permission must be obtained from the Publisher or the owner of the content,
etc., in order to reproduce or network any portion of the textual material (in any
media) that is contained in the Work.
MERCURY LEARNING AND INFORMATION (“MLI” or “the Publisher”) and
anyone involved in the creation, writing, or production of the companion disc,
accompanying algorithms, code, or computer programs (“the software”), and
any accompanying Web site or software of the Work, cannot and do not warrant
the performance or results that might be obtained by using the contents of the
Work. The author, developers, and the Publisher have used their best efforts
to insure the accuracy and functionality of the textual material and/or programs
contained in this package; we, however, make no warranty of any kind, express
or implied, regarding the performance of these contents or programs. The
Work is sold “as is” without warranty (except for defective materials used in
manufacturing the book or due to faulty workmanship).
The author, developers, and the publisher of any accompanying content, and
anyone involved in the composition, production, and manufacturing of this
work will not be liable for damages of any kind arising out of the use of (or the
inability to use) the algorithms, source code, computer programs, or textual
material contained in this publication. This includes, but is not limited to, loss
of revenue or profit, or other incidental, physical, or consequential damages
arising out of the use of this Work.
The sole remedy in the event of a claim of any kind is expressly limited to
replacement of the book and/or disc, and only at the discretion of the Publisher.
The use of “implied warranty” and certain “exclusions” vary from state to state
and might not apply to the purchaser of this product.
C++ Programming
Fundamentals
This publication, portions of it, or any accompanying software may not be reproduced in any
way, stored in a retrieval system of any type, or transmitted by any means, media, electronic
display or mechanical display, including, but not limited to, photocopy, recording, Internet
postings, or scanning, without prior permission in writing from the publisher.
The publisher recognizes and respects all marks used by companies, manufacturers, and devel-
opers as a means to distinguish their products. All brand names and product names mentioned
in this book are trademarks or service marks of their respective companies. Any omission or
misuse (of any kind) of service marks or trademarks, etc. is not an attempt to infringe on the
property of others.
Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc.
For additional information, please contact the Customer Service Dept. at (800) 232-0223 (toll
free). Digital versions of our titles are available at numerous electronic vendors.
The sole obligation of Mercury Learning and Information to the purchaser is to replace
the book and/or disc, based on defective materials or faulty workmanship, but not based on
the operation or functionality of the product.
Dedicated to our loving parents
and beloved students
Contents
Prefacexiii
Acknowledgmentsxv
MCQ-Based 55
Practical Questions 56
References57
Books57
Websites57
Chapter 6 Inheritance 97
6.1 Introduction 97
6.2 Inheritance 97
6.2.1 Access Specifiers 99
6.2.2 Inheritance Modes 101
6.3 Types of Inheritance 107
6.4 Constructor Calling 124
6.5 Implementing Inheritance 125
Summary 127
Exercises128
Theory Questions 128
Practical Questions 128
MCQ-Based129
References136
Books136
Websites137
Index269
Preface
Key Features
QQ Practical Applications: Real world analogies as practical applications are
given throughout the text to quickly grasp and connect the fundamentals
of C++ programming. This approach, in turn, will assist the reader in
developing the capability to identify the practical problems that could
be efficiently solved through an OOP approach.
QQ Programs and Output Snippets: To better understand the OOP
fundamentals at a generic level-followed by their implementation
using C++ Programming, detailed implementation codes are discussed
to elaborate real world applications along with their output snippets
throughout the book. This presentation will assist the readers in easily
understanding the subject at conceptual level and their corresponding
implementation.
QQ Multiple Choice Questions: To assist students for placement-oriented
exams in various IT fields, several exercises are suitably chosen and are
given in an MCQ format.
Acknowledgments
We are indeed grateful to Chairman VIPS- Dr. S.C. Vats, Vice Chairman VIPS-
Sh. Suneet Vats, Director General VIPS- Dr. Ashwani Kumar Sharma, and
Dean VSIT- Prof. Supriya Madan of our employer institute, i.e., Vivekananda
Institute of Professional Studies (GGS IP University). They are always a source
of inspiration for us, and we feel honored because of their faith in us.
We also take this opportunity to extend our gratitude to our mentors:
Dr. O.P. Rishi (University of Kota), Dr. Sushil Chandra (DRDO, GOI), and
Dr. Udyan Ghose (GGS IP University) for their motivation to execute this
project.
We are profoundly thankful to Ms. Stuti Suthar (SAP Labs), Mr. Sahil
Pathak (TMB), Mr. Deepanshu Gupta (Tech Mahindra Ltd.), Ms. Aditi Vats
(VIPS, GGSIPU) for helping us in proofreading and compiling the codes in this
manuscript.
It is not possible to complete a book without the support of a publisher.
We are thankful to David Pallai and Jennifer Blaney of Mercury Learning and
Information for their enthusiastic involvement throughout the tenure of this
project.
Our heartfelt regards to our parents, siblings and family members who
cheered us in good times and encouraged us in bad times.
Lastly, we have always felt inspired by our readers especially in USA, Canada,
and India. Their utmost love and positive feedback for our four authored titles
of Data Structures using C/ C++/Java/Python, published with MLI, helped us
to further improve the current title.
1
C++ and Beyond
Introduction
In this chapter, you will become familiar with the basics of C++, a powerful
programming language used by developers for its easy syntax and concepts.
Many video games, embedded systems, IoT devices, and resource-heavy AI
applications make use of C++. C++ is a general purpose and cross-platform
language that offers a vast collection of libraries to help you program with
ease. Let’s get started.
C++ Features
QQ Simple syntax: As it is derived from C, the syntax is similar and easy to
understand.
QQ Object-oriented: OOP features like polymorphism, inheritance,
encapsulation, and abstraction are used.
QQ Platform dependent: Your code will execute only on the operating
system it is designed and developed on.
QQ Provides memory management: Dynamic memory allocation is
supported by C++.
QQ Mid-level programming: It is capable of doing low-level programming
tasks, such as for drivers and kernels, and high-level applications like
games, GUI, and desktop apps.
QQ Vast libraries: You have access to many built-in functions (libraries),
which saves time.
QQ Compiler-based: Your C++ program won’t be executed without passing
the compilation barrier.
QQ Structural programming language: Your code is modular, i.e., consisting
of functions, classes, and objects.
C++ and Beyond • 3
Consider the following example. The steps needed to make a cup of instant
coffee are as follows:
Step 1. Check for the availability of coffee.
Step 2. If true, find sugar and water or else go back.
Step 3. If true, then mix all three or else go back or leave the coffee sugar
free.
Step 4. Check for the availability of milk.
4 • C++ Programming Fundamentals
Figure 1.3 Encapsulation
1. Encapsulation
Shielding data from any threat involves binding it together with methods in
objects, and so whenever we need to call upon any functionalities, our data
C++ and Beyond • 5
is provided along with them. Look at it like a capsule with all the important
ingredients you might need all in one place. C++ implements this concept
by introducing classes into our program.
2. Data Abstraction
Abstraction involves fetching only the relevant data to the user and hiding
any other details. Consider an example where you go to a restaurant and
place your order. You sometimes get an order number to pick up your
food when the number is called. You are not concerned with the tools or
number of employees working to make your meal or their details. Relevant
information sharing saves time and memory, and this protects our data.
We can implement abstraction in C++ using classes to group data
members and member functions together. This approach will determine
which data member will be accessible to which extent to other entities in
our program.
3. Polymorphism
Polymorphism provides us with multiple forms of a method with different
signatures but the same name. There are two types: runtime polymorphism
and compile-time polymorphism, both of which are implemented in C++
using method overloading and over-riding. Methods can exist in multiple
forms by varying the type of parameters and number of parameters they
take in the signature of the function. When these methods used with same
name but different signature it is called overloading and when used with
same name as well as signature is called over-riding.
Let’s consider the following example:
In Formula 1 Racing, there are 10 teams with 2 drivers each, and the drivers
are provided with the same equipment and car specifications. However, the
result attained by both drivers for their teams always differs as the “method”
(the car) has been “overloaded” in completely different ways (that is, the F1
car exists in different forms).
Figure 1.4 Polymorphism
6 • C++ Programming Fundamentals
4. Inheritance
Just as all children inherit certain qualities from their parents and
grandparents, classes in C++ can also inherit certain properties or attributes
from other classes. All you need to learn at this stage is that the class that
inherits from the parent is called the derived class, while the parent class is
called the base class. This promotes the reusability of the code blocks, and
you might not need to define all classes.
Figure 1.5 Inheritance
5. Message Passing
6. Dynamic Binding
Dynamic binding (or late binding) tells which procedure will be called at
runtime. The code we write in C++ is called the source code and it is saved
with the extension .cpp. The compiler checks each line in the program to
find any errors and notify us about them. The time it takes the program to
execute is called the runtime. That is when the function calls are executed.
The code inside our procedure is not known until execution, hence the
name late binding. In C++, it is implemented using objects.
1.4 C++ Basics
Now that you understand what can be done in C++, let us look at exactly
how it is done. Similar to mathematics, we will learn about what variables
are, as well as the symbols we will use to solve problems.
1.4.1 Variables
Variables in C++ are unique names given to units that hold value within
a defined scope. Naming is done by following certain rules. By following
these rules, you can make your program more understandable to others (as
well to yourself).
The variable declaration means introducing the variable to the program
before it is used anywhere.
A variable definition means the variable is assigned a memory location
and a value. Rules for naming variables in C++ are as follows:
//variables naming
int a,b; // declared
char ch;
int 1a; // wrong statement error
char _abc;// declared and defined
cout<<"They take value "<<a<<endl;
return 0;
}
Output:
QQ Character: used for alphabetic values. The memory space is only 1 byte.
It ranges from -128 to 127 or 0-255 for signed and unsigned char data
types.
QQ Boolean: Some statements require a logical answer, i.e., either true or
false. This is done in C++ using bool, which stores a Boolean value.
QQ Floating Point: This data type is used for storing decimal values, such as
1.2 or 1.234, up to 7 digits of precision. The keyword float is used for
this and takes up 4 bytes of memory space.
QQ Double Floating Point: This data type is also to store decimal values, but
with 15 digits of precision. The keyword used for the double floating-
point data type is double. Double variables typically require double the
space of floating point variables, i.e., 8 bytes.
QQ Void: “Void” means nothing, containing no value. However, you should
be careful not to confuse it with zero: 0 is a numeric value, while void is
valueless. It is mostly used with a function return type to signify that it
returns no value.
1. Signed: This is very useful as it stores all positive, negative values, and
even zero.
2. Unsigned: This only stores negative values.
3. Short: This is used for small integer values and ranges from
−32,767 to +32,767.
4. Long: This ranges from -2147483647 to 2147483647 and is used for
larger values.
10 • C++ Programming Fundamentals
Output:
Size of int : 4 bytes
Size of short int : 2 bytes
Size of long int : 8 bytes
Size of signed int : 4 bytes
Size of unsigned long int : 4 bytes
Size of char : 1 byte
Size of float : 4 bytes
Size of double : 8 bytes
C++ and Beyond • 11
1. Pre-processor
The first event that occurs in a C++ program is that the pre-processor
processes the program before compilation. It includes the header files
and any macros, if defined. It prepares the source code for the later stag-
es of execution.
2. Compiler
Now the pre-processed source code passes through the compiler to pro-
duce an object file. The complier translates the programming language
code in C++ into the machine language, and checks for any errors, issuing
warnings about the errors. The object file contains the assembly code.
3. Linker
The linker connects the libraries and object files together to generate an
executable file with the extension .exe.
12 • C++ Programming Fundamentals
4. Loader
The loader places your program onto the memory and this is where the
programs actually runs.
5. Another way to run code is to type it into Notepad and then save it as a
.cpp file. Open your command prompt terminal and type the run >gcc
filename.cpp command to see output.
Output:
Hello new you!!
Summary
QQ C++ is a compiled, general-purpose, case-sensitive, and free-form
programming language that supports procedural, object-oriented
programming.
QQ C++ was developed by Bjarne Stroustrup in 1980 at Bell Labs.
QQ There are programming paradigms, such as procedural, structural, and
object-oriented.
QQ C++ has OOP features, such as polymorphism, inheritance, data
encapsulation, abstraction, message passing, and late binding.
QQ We learned about C++ data types, data modifiers, and variables.
QQ We looked at the ranges for int, char, and long int.
QQ We discussed working with a compiler and debugger.
QQ We considered the stages of C++ program execution.
QQ We wrote our first program in C++ using simple steps.
14 • C++ Programming Fundamentals
Exercises
Theory Questions
1. What are the features of C++? Why do we need to learn C++?
2. List four practical field applications of C++.
3. Differentiate between types of programming paradigms.
4. Explain OOP concepts with valid examples.
5. List the rules for naming a variable. Identify the valid variable names
from the following list:
a. _thisis2
b. 24Hours
c. Name@dune
d. Formula1
e. __aditi
f. Meine#Name
c. middle-level
d. None of the above
Practical Application
1. Write a program in C++ to check the upper and lower limits of an integer.
2. Write a program in C++ to print your name and details on separate
lines.
3. Write a program in C++ to find the size of the following variable: abc.
C++ and Beyond • 17
4. Write a program in C++ to find the sizes of various data types and print
them.
5. Write a program in C++ to display the use of naming variables and their
types.
6. Write a program in C++ to check whether variable 234Mine exists.
MCQ
Answer Key
1. (c) 2. (c) 3. (b) 4. (c) 5. (d) 6. (b) 7. (c) 8. (d) 9. (a) 10. (c)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition),
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition), (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++, (BPB Publications, September, 2020).
Websites
QQ Learn CPP, accessed May 2022, https://www.learncpp.com
QQ Silly Codes, accessed May 2022, https://sillycodes.com
QQ Codes Cracker, accessed May 2022, https://codescracker.com
QQ Geeks For Geeks, accessed May 2022, https://www.geeksforgeeks.org
QQ Udacity, accessed May 2022, https://www.udacity.com
QQ Scaler, accessed May 2022, https://www.scaler.com
QQ C Plus Plus, accessed May 2022, https://cplusplus.com
CHAPTER
2
Basic Play in C++
int main() {
cout << "\nHello\tProgrammer\n\n ";
return 0;
}
Output:
Hello Programmer
2.2 Stream-Based IO
In C++, for the user to enter values, we use input streams; here, we use the
term stream to refer to a group of bytes that can be accessed sequentially.
There are two different types of streams. Input streams are used to hold
input from a user, such as the information that comes from a keyboard. For
example, the user might press keys on the keyboard, and all these keystrokes
are saved in the input stream to be used later when the program itself
requires it. Output streams are used to showcase output using a monitor, a
file, or a printer. For example, you may need a printout, but the printer is
Basic Play in C++ • 21
currently printing another document, so your data/file waits for its turn to
be given as output. To able to use all these functionalities in your C++ code,
you need to include the iostream header file, which provides with a whole
hierarchy of classes (multiple inheritance) to make use of all I/O classes.
In this section, you will work with iostream; the iostream class is derived
from ios_base. The symbols << and >> are special operators. The istream
class is for input streams. The extraction operator (>>) removes values from
the stream created when the user presses keys. The ostream class is for
output streams, and the insertion operator (<<) is used to put values in the
stream to be displayed when asked on output devises like monitors. The
iostream class can handle both input and output streams, whether it is the
user pressing random keys or an alert message to the user not to do so. This
is all accomplished through one class.
The standard stream is a stream provided to your computer program by
its own environment. C++ comes with the following predefined standard
stream objects.
1. cin is an istream class that uses standard input keys for fetching values.
2. cout is an ostream class that uses standard output, such as displaying
your result or message on the terminal.
3. err is an ostream class that uses the standard error.
4. clog is an ostream class that uses the standard unbuffered output.
cinand cout are commonly used at this stage, so be careful to not confuse
them with other operators.
int main() {
char ch= 'A';
int a =9,b=10,c;
cout << "Value as output is : " << ch<< a+b<<endl;
cout<< "Enter your input integer "<<endl;
cin>>c;
cout<< "You entered "<<c<<endl;
}
Output:
Value as output is: A19
Enter your input integer
3
You entered 3
int main() {
char ch= 'A';
int c;
cout<< "\nEnter your input integer "<<endl;
cin>>c;
cout<< "\nYou entered "<<c<<endl;
cerr << "Error message : " << ch << endl;
clog << "Error message : " << c << endl;
}
Output:
Enter your input integer
45
You entered 45
Error message : A
Error message : 45
2.3 Comments
Commenting in your program will help you keep track of how your program
works; program comments serve as notes for future reference, as well.
Basic Play in C++ • 23
These are only visible to the program and result in no output change on
the terminal.
You can include a single line or multiline comment:
QQ The /* (a slash followed by an asterisk) are special characters; after you
type /*, you write your comments (consisting of any combination of
characters), and follow them with the */ characters. This results in a
multi-line comment.
QQ For a single-line comment, you do not need the ending characters:
the // (two slashes) are followed by your comment (consisting of any
combination of characters).
Output:
Adding comments
C/C++ has many built-in operators and can be classified into 6 types:
int main() {
int a, b;
a = 78;
b = 25;
cout << "a + b = " << (a + b) << endl;
cout << "a - b = " << (a - b) << endl;
cout << "a * b = " << (a * b) << endl;
cout << "a / b = " << (a / b) << endl;
cout << "a % b = " << (a % b) << endl;
return 0;
Output:
a + b = 103
a - b = 53
a * b = 1950
a / b = 3
a % b = 3
2.5 Type Conversion
The process of converting a value from one type to another type is called
type conversion; there are two kinds of type conversion, implicit and explicit.
26 • C++ Programming Fundamentals
Implicit Conversions
QQ Done by the compiler on its own using intelligence, without any help
from the user.
QQ Like if a datatype takes a new value different than the present one, so it
upgrades it to the value to adjust without giving any errors.
Code: Implicit Conversion
#include <iostream>
using namespace std;
int main() {
return 0;
}
Output:
a = 131
b = a
c = 132
Explicit Conversions
QQ It allows us to explicitly tell the compiler to convert a value from one
type to another type, and any fault is our responsibilities.
QQ We will use the static_cast operator- static_cast<new_type>(expression).
int main()
{
double d = 1.6;
int sum = (int)d + 5;
cout << "Sum = " << sum;
Basic Play in C++ • 27
return 0;
}
Output:
Sum = 6%
2.6 Keywords
Keywords are reserved words with a special meaning associated with them.
Therefore, they cannot be used for other purposes in C++ programs. C++
reserves a set of 92 words.
Here is a list of all the C++keywords.
alignas bitand export reinterpret_cast
alignof bitor requires (since C++20)
and bool return
and_eq break short
asm case signed
auto catch sizeof
bitand char static
bitor char8_t (since C++20) static_assert
bool char16_t static_cast
break char32_t struct
case class switch
catch compl template
float concept (since C++20) this
for const thread_local
friend consteval (since throw
goto C++20) true
if constexpr try
inline constinit (since typedef
int C++20) typeid
long const_cast typename
mutable continue union
namespace co_await (since C++20) unsigned
new co_return (since using
extern C++20) virtual
false co_yield (since C++20) void
do decltype volatile
not default wchar_t
not_eq delete while
nullptr double xor
operator dynamic_cast xor_eq
or else public
or_eq enum register
private explicit protected
28 • C++ Programming Fundamentals
int main()
{
cout << "June!";
cout << "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20……..Pls No";
return 0;
}
For Loop
We can print the dates in our date program using a for loop. The general
syntax for a for loop is as follows:
for (initialization; condition; end condition)
{
//statement or for body
}
2. The second part is where the condition is checked to able to enter the
for loop.
3. Either the terms satisfying the other statements execute or the program
comes out of the loop (i.e., it terminates).
4. Lastly, the end condition is used to change the initialization for the next
round of loops, often called the next iteration. This usually involves an
increment/decrement operation.
int main()
{
for (int count= 1; count <= 30; ++count)
std::cout << count << ‘ ‘;
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 %
Here is another example of a for loop that helps us see the inner working
of for loops:
for (;;)
statement;
Output:
The result of this code is an infinite loop that needs to be terminated.
While Loop
A for loop might be too complex for our program. We do have a simpler
loop that involves having only one condition inside of it. The syntax for a
while statement is as follows:
while (condition)
{
statement;}
30 • C++ Programming Fundamentals
Inside the while loop, as long as the condition is true, we do the work.
Otherwise, we exit the loop. In the next example, we use the end condition
and start expression inside the while loop’s body for the next iteration.
#include <iostream>
int main()
{
int count=1;
while (count <= 30)
{
std::cout << count << ‘ ‘;
++count;
}
return 0;
}
while (true)
{
// this loop will execute forever
}
Basic Play in C++ • 31
Do While Loop
The do while loop is similar to the while loop, but here, the work you need
to repeat will execute at least once. The syntax for a do while loop is as
follows:
do
{statement; // can be a single statement or a compound statement}
while (condition);
int main()
{
int i = 1;
do{
std::cout<<i<<"\n";
i++;
} while (i <= 5) ;
return 0;
}
32 • C++ Programming Fundamentals
Output:
1
2
3
4
5
Nested Loops
A nested loop is a loop within a loop, and this structure allows us to perform
many functions more efficiently.
#include <iostream>
using namespace std;
int main() {
return 0;
}
Output:
*
**
***
else
statement;
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int x{};
std::cin >> x;
if (x > 10)
std::cout << x << " is greater than 10\n";
else
std::cout << x << " is not greater than 10\n";
return 0;
}
int main() {
for (int i = 0; i < 6; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
return 0;
}
Output:
0
1
2
3
5
QQ break: Breaking out of a difficult and unwanted situation is important
for the code’s “health,” so this statement terminates the loop and
executes the next statement.
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 6; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
return 0;
}
Output:
0
1
2
3
Basic Play in C++ • 35
QQ return: You might have noticed this code in the snippets presented
here. There is a return statement and int, so the code returns an
integer value.
QQ goto: What if your needed body of code is far away from the ongoing
loop? In this situation, use goto to jump directly that block of code. Use
this statement with caution.as you might loose flow control of the code
and it would be difficult to maintain the code.
#include <iostream>
using namespace std;
int main()
{
int n = 88;
if (n % 2 == 0)
goto place1;
else
goto place2;
place1:
cout << "Even" << endl;
return 0;//return statement used
36 • C++ Programming Fundamentals
place2:
cout << "Odd" << endl;
}
Output:
Even
Function Declaration
The function declaration introduces the function and what it is capable of
doing provided the necessary parameters. The compiler gets to know the
signature of the function and verifies when it is being called.
The syntax for this is as follows:
return_type function_name([ arg1_type arg1_name, ... ]) { code }
Passing Parameters to Functions
The parameters passed to a function are called actual parameters and the
parameters received by a function are called formal parameters.
Basic Play in C++ • 37
Output:
max is 20
C C++
C was developed by Dennis Ritchie in around C++ was developed by Bjarne
1969 at AT&T Bell Labs. Stroustrup in 1979.
C uses procedural programming. C++ supports both procedural and OOP
paradigms.
(Contd.)
38 • C++ Programming Fundamentals
C C++
C is a subset of C++. C++ is superset of C.
C does not support polymorphism, encapsulation, C++ has support for polymorphism,
and inheritance. encapsulation, and inheritance.
C does no data hiding and can be easily C++ encapsulation hides the data to
manipulated. ensure that data structures and operators
are used as intended.
Built-in data types are supported. Built-in as well as user-defined data
types are supported in C++.
C is a function-driven language and more C++ is an object-driven language.
attention given to the function.
The header file used is stdio.h. Iostream.h is used in C++.
C does not support function and operator C++ supports both function and
overloading. It also does not have the namespace operator overloading; it has the
feature and reference variable functionality. namespace feature and reference
variable functionality.
Functions in C are not defined inside a structure. Functions can be defined inside a
structure.
Reference variables are not supported in C. Reference variables are supported in
C++.
The namespace feature is not available. Namespaces provided by C++.
The virtual and friend functions are not supported The virtual and friend functions are not
by C. supported by C++.
Direct exception handling is not supported. Exception handling is supported.
Memory management occurs through the New and delete operators are used for
malloc() and calloc() functions memory allocation and deallocation.
Summary
QQ Literal constants (literals) are unnamed values used directly in code.
QQ The iostream class can handle both input and output streams.
QQ cin is an istream class that uses the standard input keys for fetching
values. cout is an ostream class that results in the standard output.
QQ The types of operators in C++ are unary operators (which take only one
operand), binary operators (which take in two operands), and ternary
operators (which work on three operands).
QQ The process of converting a value from one type to another type is called
type conversion.
Basic Play in C++ • 39
QQ C++ reserves a set of 92 words for its own use called keywords.
QQ C++ has loops, such as for, while, and do while, to perform repeated
tasks.
QQ The function definition and declaration are done with the signature to
call later.
QQ C++ is an improvement over C, and although there are basic
similarities, they have many differences.
Exercises
Theory Questions
1. Compare C &C++.
2. Define literals and constants in C++.
3. Discuss various types of operators in C++.
4. How is type conversion possible in C++?
5. Define all the io-based stream classes in C++.
6. What does int actually tell in a program?
7. Which is better, a for or while loop? Discuss your answer using
examples.
8. Is a do while loop more efficient than a normal while loop?
9. Define various control statements with examples.
10. Is it better to use if-else or goto? Please support your reasoning with
examples.
11. Discuss the procedure of using functions in C++.
12. Why do you think modular programming is preferred among program-
mers?
MCQ-Based
1. Which of the following features is not provided by C?
a. Pointers
b. Structures
40 • C++ Programming Fundamentals
c. References
d. Functions
Practical Questions
1. Write a program in C++ to implement operators.
2. Write a program in C++ to print your hobbies on separate lines.
3. Write a program in C++ to print the sum of three numbers.
4. Write a program in C++ to add, multiply, and subtract two numbers
from user-given inputs.
5. Write a program in C++ to calculate the volume of a cylinder with all
dimensions entered by the user.
42 • C++ Programming Fundamentals
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition),
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition), (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++, (BPB Publications, September, 2020).
Websites
QQ Learn CPP, accessed May 2022, https://www.learncpp.com
QQ Geeks For Geeks, accessed May 2022, https://www.geeksforgeeks.org
QQ Word Press, accessed May 2022, https://wordpress.com
QQ Code 2 Flow, accessed May 2022, https://code2flow.com
QQ Silly Codes, accessed May 2022, https://sillycodes.com
CHAPTER
3
Arrays and Strings
from 0 to 2. The array named Train has three coaches with the indexes as
shown in Figure 3.1.
Train(0) Train(2)
Figure 3.1 The “train” array example
Output:
Elements in Train are
Elements 1: 10
Elements 2:11
Elements 3: 12%
Arrays and Strings • 45
int num_array[6];
cout << "Enter six numbers: " << endl;
for (int i = 0; i < 6; ++i)
{
cin >> num_array[i];//take elements from user
}
cout << "The numbers are: ";
for (int j = 0; j < 6; ++j) {
cout << num_array[j] << " ";// displaying user array
}
return 0;
}
Output:
Enter six numbres:
12
79
45
33
11
23
The numbers are: 12 79 45 33 11 23
elements! You can avoid this situation by only passing the name of the array,
which acts as a pointer to the first element and whole array. It is important
to ensure that the function signature indicates it is an array by using one of
the following:
QQ int func(int array_name[]){ //body }
Output:
How many passengers 3
This can be done using the sizeof method (which gives us the number of
bytes in a particular datatype) by passing the name of the array.
return 0;
}
Output:
10
return 0;
}
48 • C++ Programming Fundamentals
Output:
Driver is: 10
Driver is: 2
3.2.4 Searching
Accessing each and every element of an array by index (called traversing) is
not efficient for large arrays, so we should work with an algorithm to search
for the element we are looking for. These search methods are as follows.
Linear Search
In a linear search, we sequentially search for the element needed by
traversing through the array and checking whether the search element
matches the array element.
1. Start.
2. Take the size and element input from a user if the array is not given.
3. Input the search element from the user.
4. Initialize the for loop from i=0 to index size-1.
5. Use a nested if loop for the search element == array[i].
6. If the result is true, then a match is found; break out of the loop.
7. If the result is false, then execute the else part of the code.
8. Stop.
}
cout<<"What do you wish to search for"<<endl;
cin>>e;
for(int i=0;i<size;i++)//traverse array
{
if(array[i]==e)//check with element to match
{
flag=i;
break;
}
}
if(flag)
cout<<"Element "<<e<<" is at index "<<flag;
else
cout<<"Element "<<e<<" is not present\n";
return 0;
}
Output:
Give the size of the array
4
Enter the elements of the array
11
23
66
77
What do you wish to search for
88
Element 88 is not present
You can also easily find the index at which the search element was found by
making a flag that is false at the start and assigning the value 1 to it inside
the if statement.
Binary Search
In this search algorithm, we are provided with a sorted array from elements
placed in order from the minimum to maximum. Now, the work is divided
in half by finding the midpoint about which the next half is found. The
program checks whether the search element is greater or smaller than
the value being searched for, and this process is repeated until the array
becomes empty and we find the matching element.
50 • C++ Programming Fundamentals
1. Start.
2. Take the size and element input from the user if the array is not given.
3. Input the search element from the user.
4. Call the binary search function and pass the array, size, firstindex, and
lastindex.
}
return 0;
}
Output:
Enter the element to search:
55
55 found at index 6 %
int main()
{
int array[3] = {{5,1,4}, {2,3,7}};
cout<<"\n2D Array:\n";
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << array[i][j]<<" ";
}
cout<<"\n";
}
cout<<"\n";
}
cout<<"\n";
}
return 0;
}
Output:
20 Array;
5 1 4
2 3 7
30 Array:
7 1 5
26 3 88
45 5 78
66 77 33
84 9 32
10 11 12
3.4 Strings
A string in C++ is a data type that represents characters that are stored as a
collection of bytes in contiguous memory locations. These are useful when
we need to work with text. The syntax for strings is as follows:
QQ string str_name = "a string"; // this only reads characters until a
whitespace is introduced
QQ char array[7] ={'c','a','r','l','o','s','\0'};//array of
characters with the last element always null to identify the end of the
string
QQ char array[] ={'c','a','r','l','o','s','\0'};
QQ char array[size]="string";
QQ char array[]="string";
int main() {
string str1;
cout << "Enter your name: ";
cin >> str1;
cout << "Name: " << str1;
return 0;
}
Output:
Enter your name:
Carlos Sainz
Name: Carlos%
Summary
QQ Array is a data type in C++ to store similar data under the same name,
and it is accessed using indexes.
QQ All array elements are stored in contiguous memory locations.
QQ The element at index 0 can also be said to be a pointer to the array
name, and the array goes up to n-1
QQ An array passes through a function using only its name.
QQ Enum is a user-defined data type.
QQ Accessing each and every element by index is called traversing an array.
QQ The elements of an array can be searched using a linear or binary
algorithm.
QQ An array of an arrays is called a multi-dimensional array.
QQ A string in C++ is a data type that represents a collection of characters
that is stored as a collection of bytes in contiguous memory locations.
QQ String functions such as concat, compare, length, and size were
discussed.
Exercises
Theory Questions
1. Discuss the concept of an array in C++.
2. How do you declare an array?
3. What are the advantages and disadvantages of arrays?
4. Explain how 2D and 3D arrays work.
5. Compare the linear and binary search algorithms for arrays.
6. What is meant by dimension and subscript with respect to arrays?
7. What is a string in C++?
8. Compare strings and character arrays.
9. Discuss various operations done on strings in C++ using examples.
Arrays and Strings • 55
MCQ-Based
1. Array elements are always stored in _________ memory locations.
a. Sequential
b. Random
c. Sequential and random
d. None of the above
Practical Questions
1. Write a program in C++ to find the largest element of a given array of
integers.
2. Write a program in C++ to print letters or your name in a string array.
3. Write a program in C++ to find the largest element in an array.
4. Write a program in C++ to find the second largest element in a given
array of integers.
5. Write a program in C++ to find the sum of elements in a given array of
integers.
6. Write a program in C++ to reverse a string.
7. Write a program in C++ to find the largest word in a string.
8. Write a program in C++ to sort a string alphabetically.
Arrays and Strings • 57
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition),
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition), (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++, (BPB Publications, September, 2020).
Websites
QQ Learn CPP, accessed June 2022, https://www.learncpp.com
QQ Geeks For Geeks, accessed June 2022, https://www.geeksforgeeks.org
QQ Silly Codes, accessed June 2022, https://sillycodes.com
CHAPTER
4
Pointers in C++
4.1 Introduction
After you work through this chapter, it is hoped that you might feel a little
more confident about using pointers in C++. What exactly is a pointer? In
programming terms, a pointer is a variable pointing towards the memory
space or the address of a given variable. A pointer holds the address of the
very first byte of the memory location where it is pointing to. This first byte
address is called the base address, and it is like a variable used to store the
address of another variable.
The concept of pointers takes time and effort to understand, but keep
practicing your coding skills while using them. With some effort, pointers
can play an important role in helping you make part of your code faster and
easier to access. You can do some important actions with pointers, even
declaring a pointer to a pointer. Let’s start with the basic declaration and
initializing process for pointers.
return 0;
}
Output:
10
030cc965f8
10
In the prior code snippet, the keyword is indicating a valid data type in
C++, and variable is the name of the pointer variable. When the data type
is taken as an integer (int), it will only point towards an integer value, i.e.,
it will be a pointer to an integer. However, a pointer can point to any part
of the memory, as this action is its sole purpose. Arithmetic operations to
be done are so done with reference to the base type. Therefore, the correct
and relevant declaration of pointers in C++ is a priority.
The pointer in the code snippet in this example is that the var value is
equal to the pointer of the address, and the & gives us this number, which
is the exact memory location where the variable is stored. Now, let’s try
visualizing how a pointer works using an image. In Figure 4.1, the cylinders
serve as the memory space with addresses “xxx” and “yyy.” The arrow shown
in the figure acts as the pointer pointing towards the memory location.
There are few more ways to declare a pointer to assign the address of
the variable. Keep in mind that changes made to references are permanent
and often irreversible. Therefore, we should use pointers with care.
In C++, we deal with null pointers. As mentioned in previous chapters,
null is not equal to zero, but indicates that the value does not exist. A null
or zero pointer points towards an address that is not legal and null. Why use
it if no reference to an address can be made? As you proceed on in your
coding journey and use pointers more often, you might face an issue where
Pointers in C++ • 61
you need to check whether the pointer is being used (for example, whether
id=s is valid). You can do this checking with the help of a null pointer.
All you need is to match the variable against a null pointer: if the value
holds true, the program will be altered because the pointer used is not legal,
helping you to make the relevant changes.
You can declare a null or zero pointer in the two ways: by either assigning
a NULL value to a pointer variable or using the keyword nullptr, as shown
in following example.
Output:
legal address not pointed
Look at the following example and try to predict the output on your own (or
you can test the code on your own computer to see what the output looks
like).
62 • C++ Programming Fundamentals
int main ()
{
int val1, val2;
int * ptr1, *ptr2, ptr3;
ptr1 = &val1;
*ptr1 = 10;
ptr1 = &val2;
*ptr1 = 20;
ptr3=50;
cout << "\nValue One = " << val1<< '\n';
cout << "Value One address = " << ptr1<< '\n';
cout << "Value two = " << val2 << '\n';
cout << "Value One address = " << ptr2<< '\n';
cout << "Value three = " << ptr3 << '\n';
cout << "Value three address = " << &ptr3 << '\n';
return 0;
}
Did you predict the output? Let us work through the code together:
The output shows how the addresses of two separate variables can be
assigned to the same pointer. The pointer of the previous value 1 will show
zero address, and then point to a new address of value 2.
Pointers in C++ • 63
4.3.1 Typecasting
In C++, we can typecast our variables from one data type to another. We
can do the same if we wish to change the assigned data type using pointers.
Let’s see an example of how this is done. We use reinterpret_cast, which
is a typecasting operator that helps convert the pointer’s data type. All it
does is change to a new type, and it does not check if the data the pointer
is pointing towards is the same or not. Its syntax is as follows (here, one
parameter is used as the pointer variable and returns no value):
data_type *var_name =
reinterpret_cast <data_type *>(pointer_variable);
Return Type
int main()
{
int* ptr= new int(69);
char* cr = reinterpret_cast<char*>(ptr);
cout << *ptr << endl;
cout << *cr << endl;
cout << ptr << endl;
cout << cr << endl;
return 0;
}
64 • C++ Programming Fundamentals
Output:
69
E
07fbbed405ac0
E
4.3.2 Passing
Passing a pointer to a function can be done in two ways: either by simply
passing the pointer or by passing a reference, as was done in some previous
examples, with simple data taken as the parameter (in this case, the data is
the pointer itself).
In the first method (simply passing the pointer), the memory addresses
of the variables are passed as parameters. Any changes made within the
function’s body will reflect on the original pointer. The following example
demonstrates this approach.
}
int main () {
int a,b;
int* num1;
int* num2;
num1= &a;
num2=&b;
cout<<"\nEnter value of Num1 and Num2:";
cin>>*num1>>*num2;
cout << "\nBefore Function Call Num1= " <<*num1 <<" Num2= "
<<*num2<<endl;
function_A( num1,num2 );
cout << "\nAfter Function Call Num1= " <<*num1 <<" Num2= "
<<*num2<<endl;
Pointers in C++ • 65
return 0;
}
Output:
Enter value of NUm1 and Num2:4
5
Before Function Call Num1= 4 Num2= 5
After Function Call Num1= 14 Num2= 19
}
int main () {
int num1;
int num2;
cout<<"\nEnter value of Num1 and Num2:";
cin>>num1>>num2;
cout << "\nBefore Function Call Num1= " <<num1 <<" Num2= "
<<num2<<endl;
function_A( num1,num2 );
cout << "\nAfter Function Call Num1= " <<num1 <<" Num2= "
<<num2<<endl;
return 0;
}
Output:
Enter value of Num1 and Num2:4
66 • C++ Programming Fundamentals
5
Before Function Call Num1= 4 Num2= 5
After Function Call Num1= 14 Num2= 19
We can easily swap numbers using pointers by passing the pointer to the
numbers and making a temporary pointer to store value. We then swap the
.
provided pointers and print the results before and after swapping.
return 0;
}
Output:
Before swapping Num1= 30 Num2= 90
After swapping Num1= 90 Num2= 30
return 0;
}
Output:
Base element :
030da805ec array[0]= 101
Second element:
030da805f0 array[1]= 102
Third element:
030da805f0 array[1] = 103%
Here, int *ptr = array; will assign the base address of the array, which
is the first element, to the pointer ptr. The following arithmetic operations
of pointers incrementing ptr will point towards the next integer in line, that
is, the second element of the array:
ptr + 1 = = &array;
ptr + 2 = = &array;……….. or
*ptr = = array[0];
*(ptr + 1) = = array;
*(ptr + 2) = = array;……….
All you need to take care of is the arithmetic to be able to access all the
elements of the 1D arrays. The same can be done to assign a pointer to all
elements of an array, that is, to the array with the following simple syntax:
data_type (*pointer_var)[Array_size];
Up until now, we have been referencing the base 0th element of the array
and accessing other elements from it. However, now the whole array falls
under the “umbrella” of one pointer. This method will help us when we
work with multi-dimensional arrays, too. How they work is explained in the
following example.
68 • C++ Programming Fundamentals
int main () {
int array[4];
int *ptr;
int *pa;
pa = array;
ptr= &array[0];
cout << "\nptr++ = "<< ptr++ << endl;
cout << "\npa++ = "<< pa++ << endl;
Output:
ptr++ = 0309abf5a0
pa++ = 0309abf5a0
In the case of multi-dimensional arrays, we can also access all the elements
using a pointer either to the base element or the whole array. When
representing 2D arrays, we use row number i and column number j as
the two parameters for defining a 2D array. We write the 2D array code as
array[i][j], so its corresponding pointer representation is *(*(arr + i)
+ j). Let us consider the following two-dimensional array:
int arr[3][4] = { {11, 22, 33, 44}, {52, 65, 75, 88}, {92, 101,
121, 152} };
int main ()
{
int array[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
int i,j;
for(i=0;i<3;i++)
{
70 • C++ Programming Fundamentals
for(j=0;j<4;j++){
cout << "*(array+"<<i<<")+"<<j <<"= "<< *(array+i)+j <<endl;
}}
return 0;
}
Output:
*(array+0)+0= 03053d95a0
*(array+0)+1= 03053d95a4
*(array+0)+2= 03053d95a8
*(array+0)+3= 03053d95ac
*(array+1)+0= 03053d95b0
*(array+1)+1= 03053d95b4
*(array+1)+2= 03053d95b8
*(array+1)+3= 03053d95bc
*(array+2)+0= 03053d95c0
*(array+2)+1= 03053d95c4
*(array+2)+2= 03053d95c8
*(array+2)+3= 03053d95cc
4.5 Pointer Use
Pointers in C++ have a wide range of use and help perform many tasks with
ease. Some of the uses of pointers are listed here.
QQ Pointers can be passed as arguments to a function by referencing it.
QQ Array items can be accessed using pointers.
QQ Pointers help in performing easy arithmetic and swapping operations to
values.
QQ Pointers can be used to return more than one value from a function with
ease.
QQ Pointers help in dynamically allocating memory.
QQ In C++, pointers help to use data structures efficiently.
QQ Pointers do valid address checking on values with the help of nullptr
or zero or a NULL pointer.
Pointers in C++ • 71
Summary
QQ A pointer holds the address of the very first byte of the memory location
where it is pointing.
QQ This first byte address is called the base address, and it is like a variable
to store the address of another variable.
QQ The & (ampersand) is used to make reference to the memory location of
another variable.
QQ A pointer needs to be dereferenced with the * (asterisk) to declare a
variable of type pointer.
QQ interpret_cast is a typecasting operator provided to us in C++ that
helps convert the pointer’s data type.
QQ A NULL or zero pointer points towards an address that is not legal and
null.
QQ Passing a pointer to a function can be done in two ways: either by
passing a value or by passing its reference.
QQ When passing by value, the copies of pointers are passed as arguments
and the changes are reflected in the original variables.
QQ When passing by reference, the addresses are directly passed as
arguments, hence the changes are permanent.
QQ Pointers also help to access array elements by either the base element
reference or the array pointer assigned.
72 • C++ Programming Fundamentals
QQ Pointers in C++ have a wide range of use and help perform many tasks
with ease.
Exercises
Theory Questions
1. Define a pointer and how it works in C++.
2. How are pointers declared and initialized?
3. What is the usage of the pointer in C++?
4. Discuss pointer arithmetic with a few examples.
5. What is the use of a null pointer in C++? How do we declare it?
6. Write down the difference between an array pointer and base address
pointer.
7. How does a null pointer help check address validity in C++?
8. List some drawbacks of using pointers. Support your reasons with
examples.
9. What is the difference between a reference and a pointer in C++?
Practical Questions
1. Write a program to print the address of a variable and input its value
from the user.
2. Write a program in C++ to swap two numbers using pointers.
3. Write a program in C++ to swap the first two characters of your name
with a pointer as the argument.
4. Write a program in C++ to perform simple arithmetic operations on
four different types of pointers.
5. Write a program in C++ for a simple calculator with a menu using only
pointer variables.
6. Write a program in C++ to input an array of addresses from a user and
print each of these addresses using a pointer.
7. Write a program in C++ to display the difference between passing by
value and passing by reference for a pointer variable.
Pointers in C++ • 73
ptr1= ptr2 ;
a. b = =a
b. ptr1 points to y
c. a = =b
d. ptr2 points to x
MCQ
Answer Key
1. (a) 2. (c) 3. (c) 4. (b) 5. (a) 6. (c) 7. (b) 8. (d) 9. (b) 10. (d)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition)
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition) (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++ (BPB Publications September, 2020).
QQ Y. Kanetkar, Test Your C++ Skills (BPB Publications March, 2003).
Websites
QQ Learn CPP, accessed July 2022, https://www.learncpp.com
QQ Codes Cracker, accessed July 2022, https://codescracker.com
QQ Geeks For Geeks, accessed July 2022, https://www.geeksforgeeks.org
QQ C Plus Plus, accessed July 2022, https://cplusplus.com
QQ Silly Codes, accessed July 2022, https://sillycodes.com
CHAPTER
5
Classes in C++
std:: cout << "\nTiger's pet name is: " << tigers;
}
};
int main() {
Felidae object1;
object1.cats = "checo";
object1.tigers = "maxial";
object1.petName();
return 0;
}
Output:
Cat's pet name is: checo
Tiger's pet name is: maxial%
Let’s take a look into how this code works. Try to predict the execution flow
to improve your understanding.
class Myclass
{
public:
int x=40,y;
void sum()
{
std::cout << "\nSum is: " <<x+y;
}
};
int main() {
Myclass c1;
Myclass c2, c3;
c1.y= 10;
c2.y = 20;
c1.sum();
c2.sum();
return 0;
}
Output:
Sum is: 50
Sum is: 60%
Characteristics of Constructors:
}
};
int main() {
Driver d1;
return 0;
}
Output:
This is a constructor of class Driver
Observe that as soon as the object is created, the constructor of the class
is called upon, as it has the ability to be overloaded. Let us now define the
various types of constructors.
1. Default Constructors
These take up no arguments and all objects of the class are initialized
with the same set of values. These are given by the compiler, and they
will be 0 or any integer value. If the programmer forgets to define a
constructor explicitly in C++, the compiler will provide them with the
default constructor implicitly. The syntax for writing the default con-
structor is as follows:
class class_name
{ class_name()
{ //body
}
};
Class in C++ • 81
};
int main() {
People Object1;
return 0;
}
Output:
This is a default constructor
Code: Implementing Parameterized Constructors
#include <iostream>
using namespace std;
class People
{
public:
int x;
};
int main() {
People Object1;
cout<<"\nWill be provided with any random value:
"<<object1.x<<endl;
//Garbage value would be shown as x is not initialized
return 0;
}
Output:
Will be provided with any random value: 9015333
82 • C++ Programming Fundamentals
2. Parameterized Constructors
In a parameterized constructor, we can pass one or more arguments to
the member function so as to assign different initialization values to an
object as it is created. Keep in mind that to call this type of constructor,
we must use the correct order and type of arguments as defined in the
constructor’s prototype. The syntax for a parameterized constructor is as
follows:
class class_name
{ class_name(argument list..)
{ //body
}
};
Code: Using Parameterized Constructors
#include <iostream>
using namespace std;
class Student
{
public:
Student(string n)
{
std::cout << "\nThis is a parameterized constructor" <<endl;
std::cout << "\nName is " <<n<<endl;
}
};
int main() {
Student s1("Mary");
return 0;
}
Output:
This is a parameterized constructor
Name is Mary
3. Copy Constructors
A copy constructor helps to create a copy of another object of a class. The
copy is created with all the same values for all data members. The syntax
for a copy constructor is as follows:
class Class_name
{ Class_name(argument list..)
Class in C++ • 83
{ //body
}
Class_name(const Class_name)
{ //body
}
};
Code: Using the Copy Constructor
#include <iostream>
using namespace std;
class Student
{
public:
string n;
/*Student()
{
std::cout << "\nThis is a default constructor \n" <<endl;
}*/
Student(string n)
{
std::cout << "\nName is " <<n<<endl;
}
Student(const Student& s1)
{
std::cout << "\nThis is a copy constructor\n" <<endl;
}
};
int main() {
//Student s1;
Student s1("Rio");
Student s3(s1);
return 0;
}
Output:
Name is Rio
This is a copy constuctor
Code: Using Constructors
#include <iostream>
using namespace std;
class Student
84 • C++ Programming Fundamentals
{
public:
Student()
{
std::cout << "\nThis is a default constructor \n" <<endl;
}
Student(string n)
{
std::cout << "\nThis is a parameterized constructor" <<endl;
std::cout << "\nName is " <<n<<endl;
}
Student(const Student& s2)
{
std::cout << "\nThis is a copy constructor\n" <<endl;
}
};
int main() {
Student s1;
Student s2("Mary ");
Student s3(s2);
return 0;
}
Output:
This is a default constructor
Name is Mary
Destructors are called when an object is not in use any more and in need
of deletion. They help with memory utilization so unused objects don’t
take up needed space. A destructor is automatically called by the compiler
whenever the object seems out of scope. If you wish to do the destruction
manually, you use the tilde (~). Let us see some of the destructor’s features.
Characteristics of Destructors:
return 0;
}
Output:
This a default constructor
86 • C++ Programming Fundamentals
class Average {
private:
int num1;
int num2;
int r;
public:
Average (int num1, int num2) {
this->num1 = num1;
this->num2 = num2;
}
void AvgResult() {
cout<<"\nAverage of num1 and num2 = "<<(this-
>num1+this->num2)/2<<endl;
}
};
int main () {
Average object1(22, 33);
object1.AvgResult();
return 0;
}
Output:
Average of num1 and num2 = 27
{
cout << "\nSum is = " << x+y<<endl;
}
static int assign(int x)
{
cout << "\nAssigned value to integer= " << x<<endl;
}
void avg()
{
r= (num1+y)/2;
cout << "\nAverage is = " << r<<endl;
cout << "\nName is " << n<<endl;
}
private:
string n="Joey";
};
int myclass::num1=4560;
int main()
{
myclass obj1,obj2,obj3;
myclass::assign(45);
obj2.avg();
obj2.sum(20,27);
cout << "\nThe static variable value : " <<obj1.num1<<endl;
return 0;
}
Output:
Assigned value to integer= 45
Average is = 2330
Name is Joey
Sum is = 47
The static variable value : 4560
In the previous code, you might have observed a new symbol (::), which
is called a scope resolution operator in C++. Its primary role is to access or
assign value to static members of a class.
C++ has a feature that enables inline functions in a class, where the compiler
copies the code of a function body whenever it is called upon. This produces
faster results, and so we, as programmers, do not have to write code for it
again and again. The syntax for calling inline functions is as follows:
inline returnType function_Name(Argument List….)
{ // function body}
class myclass
{
public :
static int num1;
static int assign(int x)
{
cout << "\nAssigned value to integer= " << x<<endl;
}
};
int myclass::num1=4560;
int main()
{
myclass obj1;
myclass::assign(87);
cout << "\nThe static variable value : " <<obj1.num1<<endl;
return 0;
}
Output:
Assigned value to integer= 87
The static vaiable value : 4560
1. Useful for situations where we are not aware of the size of a particular
data type until runtime
2. To make a group of data types more flexible and modifiable by the user
3. User input given more attention and results become more personalized
New Operator
The new operator in C++ helps in dynamically allocating memory . We
make a request for memory space and if the required amount of memory
is there, then the specified amount of memory is allocated and returns a
pointer to it (or null, if it failed to allocate). Sizeof can be used to compute
its size. The syntax for this operator is as follows:
Pointer = new dataType;
Datatype *new datatype [size in int];
pointerVar = new Datatype[int size];
Delete Operator
The delete operator in C++ helps in dynamically deallocating memory.
The address becomes invalid, and the memory is now used by different
data, so it returns void. If an object is allocated using the new operator, then
it can only be deleted using the delete operator. This operator ensures safe
and efficient memory use. The syntax for the delete operator is as follows:
delete ptr_var;
Code: Using the Delete Operator
#include <iostream>
using namespace std;
int main () {
int *ptr1 = nullptr;
ptr1 = new int;
*ptr1 = 28;
cout << "\nValue of pointer variable 1 : " << *ptr1 << endl;
delete ptr1;
return 0;
}
Output:
Value of pointer variable 1 : 28
92 • C++ Programming Fundamentals
Summary
QQ A class is a user-defined data type consisting of methods and data
grouped together as members.
QQ A constructor’s main role is to initialize a class, and it constructs the
value of all the data members.
QQ Three types of constructors are default, parameterized, and copy.
QQ Destructors help in deallocating the memory of an unused object.
QQ Constructors and destructors both have the same name as of the class.
QQ The this pointer in C++ that stores the address of an object or class
instance enables the member function to update the correct object
values.
QQ Class functions can either be defined inside or outside the class
definition.
QQ Calling class functions is carried out using objects of the class through
the dot or selection operator.
QQ In C++, the static keyword declares any variable, data members, or
functions as a type of constant. The values cannot be modified.
QQ :: is the scope resolution operator in C++, and its primary role is to
access or assign value to static members of a class.
QQ The new and delete operators are used for memory allocation and
deallocation in C++.
Exercises
Theory Questions
1. What is a class? Describe the syntax for declaring a class with examples.
2. Discuss class making and declaration in C++?
3. What is the difference between member functions defined inside and
outside the body of a class?
4. Explain the different methods of passing object parameters.
5. Discuss constructors and destructors in C++ using examples.
Class in C++ • 93
4. When struct is used instead of the keyword class means, what will
happen in the program?
a. access is public by default
b. access is private by default
c. access is protected by default
d. access is denied
MCQ
Answer Key
1. (a) 2. (a) 3. (c) 4. (a) 5. (b) 6. (c) 7. (b) 8. (d)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition)
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition) (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++ (BPB Publications September, 2020).
QQ Y. Kanetkar, Test Your C++ Skills (BPB Publications March, 2003).
Websites
QQ Learn CPP, accessed July 2022, https://www.learncpp.com
QQ Codes Cracker, accessed July 2022, https://codescracker.com
QQ Geeks For Geeks, accessed July 2022, https://www.geeksforgeeks.org
QQ Udacity, accessed July 2022, https://www.udacity.com
QQ Scaler, accessed July 2022, https://www.scaler.com
QQ C Plus Plus, accessed July 2022, https://cplusplus.com
CHAPTER
6
Inheritance
6.1 Introduction
We discussed object-oriented programing concepts briefly in the first
chapter. Now, let’s learn a few of them in depth. We are familiar with class
making and how objects access them to use the members of a particular
class. In C++, we can make multiple classes in one program (and make
connections between these classes) and enable them to share access to
their individual data members. This concept of establishing a relationship
between classes where some of the properties are shared is referred to as
inheritance. This chapter examines inheritance and its type and how you
can make full use of this object-oriented programing concept. All topics
discussed have code examples, and readers are encouraged to try them all
to improve their understanding of this topic.
6.2 Inheritance
Just as a child inherits not only the assets of their parents but also some
unique features, like eye or hair color, inheritance in C++ is defined as the
ability of a “child” class to inherit features of its “parent” class. Let’s learn a
little more about these terms before we proceed.
QQ Parent class: Also known as the base class or super class. You can think
of it as the entity that existed before its children. All of its children
inherit properties from it.
98 • C++ Programming Fundamentals
QQ Child class: Also known as the derived class or sub class. This is a class
that is made out of the certain features of the base class.
Figure 6.1 Inheritance
In Figure 6.1, the arrow going downward shows the relationship between
the classes. Can you identify the base class and sub class? The parent is
the base class, and the child is a derived class. Let’s declare and define the
relationship shown in Figure 6.1. The syntax is as follows:
class Child : access_specifier Parent
{
// class body
};
Code: Working with Inheritance
#include <iostream>
using namespace std;
class Parent {
public:
int p=60;
void showP()
{
cout<<"\nParent age is " <<p<< endl;
}
};
class Child : public Parent
{
public:
int c=20;
Inheritance • 99
void showC() {
cout<< "\nChild age is " <<c<< endl;
}
};
int main() {
Child c1;
c1.showP();
c1.showC();
return 0;
}
Output:
Parent age is 60
Child age is 20
Code Debriefing
QQ As you can observe from the preceding code, we have established a
relationship between two classes using inheritance.
QQ The child class will now be able to inherit and even modify properties
from the parent class.
QQ The objects of the child class can access the member functions of the
base or parent class.
public:
int p1=60;
void showP()
{
cout<<"\nParent age is public " <<p1<< endl;
cout<<"\nParent age is private " <<p2<< endl;
cout<<"\nParent age is protectd " <<p3<< endl;
}
private:
int p2=12;
protected:
int p3=16;
};
public:
int c1=20;
void showC() {
cout<< "\nChild age is public " <<c1<< endl;
cout<< "\nChild age is private " <<c2<< endl;
cout<< "\nChild age is protected " <<c3<< endl;
}
private:
int c2;
protected:
int c3;
};
int main() {
Child c;
c.p2= 36;
c.p3=56;
c.showP();
c.showC();
return 0;
}
Inheritance • 101
Output:
Carefully study the given code snippet and the errors that resulted as we
tried to access data members declared as private and public in the derived
class calls.
};
class PublicChild : public parentc
{
public:
int pro()
{
return avgSal;
}
};
102 • C++ Programming Fundamentals
int main()
{
PublicChild obj1;
cout << "\nPrivate : adharnumber digit is inaccessible as
it is not inherited " << endl;
cout << "\nProtected<->Protected :avg salary is "
<< obj1.pro() << endl;
cout << "\nPublic<->Public : age is " << obj1.agep << endl;
cout<< "\n";
return 0;
}
Output:
Private: adharnumber digit is inaccessible as it is not inherited
Protected<->Protected :avg salary is 43000
Public<->Public : age is 52
Code Debriefing
QQ As you can see from the code, we have established a relationship
between two classes using public inheritance.
QQ The public child class will now be able to inherit and even modify
properties from the parent class members, as their access is declared
in the base class.
QQ An object of the child class can access all the members except the
private ones of the base or parent class.
private :
int adharDigit=876;
};
class PublicChild : public parentc
{
public:
int pro()
{
return avgSal;
}
};
int main()
{
PublicChild obj1;
cout << "\nPrivate : adharnumber digit is inaccessible as
not inherited " << endl;
cout << "\nProtected<->Protected :avg salary is "
<< obj1.pro() << endl;
cout << "\nPublic<->Public : age is " << obj1.agep << endl;
cout << "\n";
return 0;
}
Output:
Private: adharnumber digit is inaccessible as not inherited
Protected<->Protected :avg salary is 43000
Public<->Public : age is 52
Code Debriefing
QQ In this code, we have established a relationship between two classes
using private inheritance.
QQ The private child class will now be able to inherit and even modify
properties from the parent class members as their access is declared in
the base class.
QQ The objects of the child class can access all the members except the
private ones of the base or parent class.
QQ The new access specifier assigned to all of the inherited material is now
private.
104 • C++ Programming Fundamentals
};
class ProtectChild : protected parentc
{
public :
int pro()
{
return avgSal;
}
int pub()
{
return agep;
}
};
int main()
{
ProtectChild obj1;
cout << "\nPrivate : adharnumber digit is inaccessible "
<< endl;
cout << "\nProtected<->Protected : avg salary is "
<< obj1.pro() << endl;
cout << "\nPublic<->Protected: age is " << obj1.pub()
<< endl;
cout<<"\n";
return 0;
Inheritance • 105
Output:
Private : adharnumber digit is inaccessible
Protected<->Protected : avg salary is 43000
Public<->Protected: age is 52
Code Debriefing
QQ In this code, we have established a relationship between two classes
using protected inheritance.
QQ The protected child class will now be able to inherit and even modify
properties from all parent class members as their access is declared in
the base class.
QQ Objects of the child class can access all the members except the private
ones of the base or parent class.
QQ The new access specifier now assigned to all of the inherited material is
protected.
The following code blocks are a few more examples to explain the types
of declared inheritance in C++. Try these out on your own to get a better
understanding of the concepts we discussed.
public:
int p1=60;
void showP()
{
cout<<"\nParent age is public " <<p1<< endl;
cout<<"\nParent age is private " <<p2<< endl;
cout<<"\nParent age is protecetd " <<p3<< endl;
}
private:
int p2=12;
protected:
int p3=16;
};
106 • C++ Programming Fundamentals
public:
int c1=20;
void showC() {
cout<< "\nChild age is public " <<c1<< endl;
cout<< "\nChild age is private " <<c2<< endl;
cout<< "\nChild age is protected " <<c3<< endl;
}
private:
int c2;
protected:
int c3;
};
int main() {
Child c;
c.p2= 36;
c.p3=56;
c.showP();
c.showC();
return 0;
}
Output:
Carefully study the given code snippet and errors that resulted when we
tried to access the inheritance declared as private in the derived class calls.
The access rules might seem difficult to understand, as their combination
creates a nine-member set of how class and class members can be inherited.
Inheritance • 107
Inherited as Public
Base Class Derived Class
Public Public
Private Inaccessible
Protected Protected
Inherited as Private Inherited as Protected
Base Class Derived Class Base Class Derived Class
Public Private Public Protected
Private Inaccessible Private Inaccessible
Protected Private Protected Protected
1. Single Inheritance
Single inheritance is the most basic type of inheritance, where there is
only one parent and one child inherits the properties. You can think of it
as a stepladder with two steps connected to one another. The syntax for
single inheritance is as follows:
class parent
{
// class body
};
class child : accessMode parent
{
// class body
};
public:
int p=60;
void showP()
{
cout<<"\nParent age is " <<p<< endl;
}
};
class Child : public Parent
{
public:
int c=20;
void showC() {
cout<< "\nChild age is " <<c<< endl;
}
};
int main() {
Child c1;
c1.showP();
c1.showC();
return 0;
}
Output:
Parent age is 60
Child age is 20
Code Debriefing
QQ As you can observe from the preceding code, we have established a
relationship between the two classes using single inheritance.
QQ Here, only the child class will now be able to inherit and modify
properties from all members of the parent class, as their access is
declared in the base class.
QQ Objects from the child class can access all the members except the
private ones of the base or parent class.
Inheritance • 109
2. Multilevel Inheritance
Multilevel inheritance, as the name suggests, has multiple levels of prop-
erty sharing. The bottom level does not directly inherit the properties,
but still can access all of the top levels’ data members. You can think of
it in terms of family relationships. This type of inheritance is similar to
how a grandchild often has a few features from his grandfather. Objects
created only for the grandchild will be able to access all of its preceding
classes. The syntax for multilevel inheritance is as follows:
class A
{
// class body
};
class B : accessMode A
{
// class body
};
class C : accessMode B
{
// class body
};
public:
int p=60;
110 • C++ Programming Fundamentals
void showP()
{
cout<<"\nParent age is " <<p<< endl;
};
public:
int c=20;
void showC() {
cout<< "\nChild age is " <<c<< endl;
};
class Grandchild : public Child
{
public:
int g=4;
void showg() {
cout<< "\nGrandchild age is " <<g<< endl;
;
}
};
int main() {
Grandchild g1;
g1.showP();
g1.showC();
g1.showg();
return 0;
}
Output:
Parent age is 60
Child age is 20
Grandchild age is 4
Inheritance • 111
Code Debriefing
QQ As you can see from the code, we have established a relationship
between three classes using multilevel inheritance.
QQ Here, the grandchild class will now be able to inherit and modify
properties from the parent and child class, as their access is declared in
the base class.
QQ Objects from the grandchild class can access all the members except the
private ones of the base or parent class.
3. Multiple Inheritance
Multiple inheritance is when a class inherits properties from two other
classes. It has many uses, and the objects created for the bottom-level
class can access all members of both of the top classes. The syntax for
multiple inheritance is as follows:
class A
{
// class body
};
class B
{
// class body
};
class C : accessMode A, accessMode B
{
// class body
};
float cost;
public:
void getdata()
{
cout<<"Enter Seat Section & Cost: "<<endl;
cin>>ss>>cost;
}
void showdata()
{
cout<<"Seat : "<<ss<<endl;
cout<<"Cost: "<<cost<<endl;
}
};
class ring2
{
private:
float spectators[3];
public:
void getdata()
{
int i;
for(i=0;i<3;i++)
{
cout<<"\nEnter "<<i+1<<" Section Spectators ";
cin>> spectators[i];
}
}
void showdata()
{
int i;
for(i=0;i<3;i++)
{
cout<<"\n"<<i+1<<"Section Spectators= "<<spectators[i];
}
}
};
public:
ring1 r1;
ring2 r2;
void getdata()
{
r1.getdata();
cout<<"Enter guest";
cin>>guest;
r2.getdata();
}
void showdata()
{
cout<<"\nGuest count= "<<guest<<endl;
r2.showdata();
}
};
int main()
{
arena obj1;
obj1.getdata();
obj1.showdata();
return 0;
}
Output:
Enter Seat Section & Cost:
4
3500
Enter guest4
Guest count= 4
1Section Spectators= 230
2Section Spectators= 345
3Section Spectators= 445%
114 • C++ Programming Fundamentals
Code Debriefing
QQ In this code, we established a relationship between three classes using
multiple inheritance.
QQ Here, the child class will be able to inherit and even modify properties
from the two parent classes, as their access is declared in the base class.
QQ The objects of the child class can access all the members, except the
private ones of the base or parent class.
4. Virtual Inheritance
Virtual inheritance comes into play when we have multiple inheritance,
but the two classes inheriting from one super class in different base class-
es have the same name. Now, the child of these two base classes will have
two copies of the super class methods from both the parents, which is
referred to as the diamond problem. The diamond problem occurs when
an object accessing a method by a name will get confused as to which
inherited method of the super class is being called. The solution to this
problem is using the virtual inheritance feature in C++, where the two
parents inherit virtually from the super class.
};
};
class exam: public virtual pg
{
public :
116 • C++ Programming Fundamentals
int ecode;
void display3()
{
cout<<"Enter exam code"<<endl;
cin>>ecode;
}
};
class external : public student, public exam
{
public :
int marks;
void display4()
{
cout<<"Enter your Level 1 marks"<<endl;
cin>>marks;
}
void check()
{
if ((age>17 )&&(marks>65))
{
cout<<"\nAllowed for Level 2 Examination\n";
}
else
cout<<"Start looking for backups";
}
};
int main()
{
external e;
cout<<"Enter your valid information"<<endl;
e.display1();
e.display2();
e.display3();
e.display4();
e.check();
return 0;
}
Output:
Enter your valid information
Enter your age
Inheritance • 117
20
Enter your name
Yash
Enter exam code
23099
Enter your internal marks
68
5. Hierarchical Inheritance
Hierarchical inheritance is when a single base class inherits multiple de-
rived classes. This inheritance has a tree-like structure, since every class
acts as a base class for one or more child classes. The syntax for hierarchi-
cal inheritance is as follows:
class A
{
// class body
};
class B : accessMode A
{
// class body
};
class C : accessMode A
{
// class body
};
class D : accessMode B
{
// class body
};
118 • C++ Programming Fundamentals
class E : accessMode C
{
// class body
};
{
f1Car :: getdata();
cout<<"Enter light motor number: ";
cin>>LmotrNO;
}
void showdata()
{
f1Car:: showdata();
cout<<"LMotor No = "<<LmotrNO<<endl;
}
};
class hyrdrolic : public f1Car
{
protected:
float price;
public :
void getdata()
{
f1Car :: getdata();
cout<<"Enter heavy motor price: ";
cin>>price;
}
void showdata()
{
f1Car :: showdata();
cout<<"HMotor Price = "<<price<<endl;
}
};
class fuel: public engine
{
protected :
int capacty;
public:
void getdata()
{
engine :: getdata();
cout<<"Enter Gear motor capacity: ";
cin>>capacty;
}
120 • C++ Programming Fundamentals
void showdata()
{
engine :: showdata();
cout<<"GMotor Capacity = "<<capacty<<endl;;
}
};
class nofuel : public engine
{
protected :
int capacty;
public:
void getdata()
{
engine :: getdata();
cout<<"Enter Non Gear motor capacity: ";
cin>>capacty;
}
void showdata()
{
engine :: showdata();
cout<<"NonGMotor Capacity = "<<capacty<<endl;;
}
};
class race : public hyrdrolic
{
protected :
int passNo;
public:
void getdata()
{
hyrdrolic :: getdata();
cout<<"Enter passenger capacity: ";
cin>>passNo;
}
void showdata()
{
hyrdrolic:: showdata();
cout<<"Passenger Capacity = "<<passNo<<endl;;
}
Inheritance • 121
};
class sprint : public hyrdrolic
{
protected :
int maxLoad;
public:
void getdata()
{
hyrdrolic :: getdata();
cout<<"Enter max goods load: ";
cin>>maxLoad;
}
void showdata()
{
hyrdrolic :: showdata();
cout<<"GMotor Capacity = "<<maxLoad<<endl;;
}
};
int main()
{
fuel f1;
race r1;
cout<<"Enter details of vehicle: "<<endl;
f1.getdata();
r1.getdata();
cout<<"Vehicle Specifications are: "<<endl;
f1.showdata();
r1.showdata();
}
Output:
Enter details of vehicle:
Enter team name
Redbull
Enter light motor number: 27789
Emter Gear motor capacity: 4900
Enter team name
Redbull
Enter passenger capacity: 1
Vehicle Specifications are:
Team Name : Redbull
122 • C++ Programming Fundamentals
LMotor No = 27789
GMotor Capacity = 4900
Team Name : Redbull
HMotor Price = 450000
Passenger Capacity = 1
6. Hybrid Inheritance
Lastly, hybrid inheritance is a mixture of all the types of inheritance we
have learned.
Code: Working with Hybrid Inheritance
#include <iostream>
using namespace std;
class pg
{
public:
int age;
void display1()
{
cout<<"Enter your age"<<endl;
cin>>age;
}
};
};
class exam
{
public :
int ecode;
void display3()
Inheritance • 123
};
class external : public student, public exam
{
public :
int marks;
void display4()
{
cout<<"Enter your Level1 marks"<<endl;
cin>>marks;
}
void check()
{
if ((age>17 )&&(marks>65))
{
cout<<"\nAllowed for Level 2 Examination :)\n";
}
else
cout<<"Start looking for backups :(( \n";
}
};
int main()
{
external e;
cout<<"Enter your valid information"<<endl;
e.display1();
e.display2();
e.display3();
e.display4();
e.check();
return 0;
}
124 • C++ Programming Fundamentals
Output:
Enter your valid information
Enter your age
20
Enter your name
Mick
Enter exam code
203
Enter your Level 1 marks
24
Start looking for backups
Remember
QQ The base class constructor is always called first, irrespective of the
object made.
QQ Derived class object creation results in initializing all of its members,
but it has inherited members, too. Hence, the base class constructor is
called first to enable all members to initialize in the derived class.
QQ In the case of multiple inheritance, the base class order of placement
will decide which constructor is called.
QQ Destructors are always called in the opposite order of the constructors.
};
class C : accessMode B
{
// class body
C();
};
C object;
};
class student : public person
{
public :
int ugYear;
void display2()
{
cout<<"Enter your Under Graduate passing Year"<<endl;
cin>>ugYear;
}
};
class exam: public student
{
public :
void check()
{
if((age>18) && (ugYear== 2021 || ugYear== 2022))
cout<<"You Can appear for CAT 2022"<<endl;
else
cout<<"Sorry you Cannot appear for CAT 2022"<<endl;
Inheritance • 127
};
int main()
{
exam e;
cout<<"Enter valid information"<<endl;
e.display1();
e.display2();
e.check();
return 0;
}
Output:
Enter valid information
Enter your age
19
Enter your under Graduate passing year
2023
Sorry you cannot appear for CAT 2022
Do your own “code debriefing” of this code and try making your own
versions of inheritance in C++.
Summary
QQ Inheritance in C++ allows a child class to inherit features of its parent
class.
QQ The parent class (or the base class or super class) is a single entity that
existed before the child class, and all its children inherit properties from
it.
QQ The child class (or the derived class or sub class) is made out of certain
features of the base class.
QQ Data members declared public can be accessed by any class, irrespective
of the relationship its class has with other classes.
QQ Data members declared private have limited access available to only the
base, friend, and derived classes.
QQ Data members declared protected can be accessed by base class
members and friend classes.
128 • C++ Programming Fundamentals
Exercises
Theory Questions
1. What is inheritance? Explain the need for inheritance with suitable
examples.
2. What are the differences between the access specifiers private and
protected?
3. What are base and derived classes?
4. Explain the syntax for declaring the derived class. Draw an access
privilege diagram for the members of a base and a derived class.
5. What are the different forms of inheritance supported by C++? Explain
them with an example.
6. Can a base class access members of a derived class? Give reasons.
7. What is accessibilty mode? What are the different inheritance visibility
modes supported by C++?
8. What are the differences between inheriting a class with public and
private visibility modes?
Practical Questions
1. Write a program in C++ to create a base class called Stack and a
derived class called MyStack. Write a program to use these classes for
manipulating objects.
2. Write a program in C++ to declare two classes named Window and
Door. Derive a new class called House from those two classes. The
Window and Door base classes must have attributes that reflect a happy
Inheritance • 129
c. Error
d. Segmentation Fault
public:
virtual void func(){
cout<<"Hello this is class A\n";
}
};
class B: public A{
int a = 15;
public:
void func(){
cout<<"Hello this is class B\n";
}
};
class B: public A
{
int a = 15;
Inheritance • 133
public:
B(){
cout<<"Constructor of class B\n";
}
};
t.print();
return 0;
}
a. In find
b. In course
c. Compiler Error: Ambiguous call to print()
d. None of the above
15. Assume that an integer takes 4 bytes and there is no alignment in the
following classes. Predict the output.
#include<iostream>
using namespace std;
class base {
int arr[10];
};
class b1: public base { };
class b2: public base { };
class derived: public b1, public b2 {};
int main(void)
{
cout << sizeof(derived);
return 0;
}
a. 40
b. 80
c. 0
d. 4
class Base {
private:
int i, j;
public:
Base(int _i = 0, int _j = 0): i(_i), j(_j) { }
};
136 • C++ Programming Fundamentals
17. A class serves as a base class for many derived classes; this is called
a. polymorphism
b. multipath inheritance
c. hierarchical inheritance
d. none of the above
MCQ
Answer Key
1. (b) 2. (d) 3. (c) 4. (b) 5. (d) 6. (a) 7. (a) 8. (c) 9. (d) 10. (c)
11. (c) 12. (b) 13. (d) 14. (b) 15. (b) 16. (b) 17. (c)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition)
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition) (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++ (BPB Publications September, 2020).
QQ Y. Kanetkar, Test Your C++ Skills (BPB Publications March, 2003).
Inheritance • 137
Websites
QQ Learn CPP, accessed July 2022, https://www.learncpp.com
QQ Codes Cracker, accessed July 2022, https://codescracker.com
QQ Geeks For Geeks, accessed July 2022, https://www.geeksforgeeks.org
QQ Udacity, accessed July 2022, https://www.udacity.com
QQ Scaler, accessed July 2022, https://www.scaler.com
QQ C Plus Plus, accessed July 2022, https://cplusplus.com
QQ Silly Codes, accessed July 2022, https://sillycodes.com
CHAPTER
7
Polymorphism
7.1 Introduction
Another important object-oriented programming concept is polymorphism.
We briefly touched on it in the first chapter with the Formula 1 example.
Polymorphism provides us with multiple forms of a method with different
signatures but the same name. Methods can exist in multiple forms by
varying the types of parameters and the number of parameters they take
in the signature of a function. For example, in Formula 1 racing, there
are 10 teams with 2 drivers each. Both drivers are provided with the
same equipment and car specifications. However, the result attained by
the drivers and their teams always differs as the car (which would be our
programming method. has been modified into completely different styles:
an F1 car can exist in different forms.
Figure 7.1 Polymorphism
140 • C++ Programming Fundamentals
int main()
{
display(11);
display(11.11);
display("Eleven");
return 0;
}
Polymorphism • 141
Output:
Integer is 11
Integer is 11
Character is Eleven
Code Debriefing
QQ This code shows that the display function of our class exists in multiple
forms.
QQ This type of polymorphism is implemented using function overloading.
QQ The functions all have the same name but different signatures. That is,
they have different combinations and numbers of parameters.
QQ While calling the display function, keep in mind which signature calls
which function.
return 0;
}
Output:
Polymorphism of addition method
Addition method 1 = 132
Addition method 2 = 154.1
Addition method 3 = 89
142 • C++ Programming Fundamentals
Code Debriefing
QQ In this code, the addition function of our class exists in multiple forms.
QQ This type of polymorphism is implemented using the function
overloading of the addition method.
QQ The functions all have the same name, but different signatures. That is,
they have different combinations and numbers of parameters.
QQ While calling the display function, keep in mind which signature calls
which function.
};
class student : public person
{
public :
int ugYear;
void display2()
{
cout<<"Enter your Undergraduate Year "<<endl;
cin>>ugYear;
}
};
class exam: public student
{
public :
void check()
{
if((age>18) && (ugYear== 2021 || ugYear== 2022))
cout<<"You can appear for Common Admission Test
2022"<<endl;
else
cout<<"Sorry, you cannot appear "<<endl;
};
int main()
{
exam e;
cout<<"Enter your valid information"<<endl;
e.display1();
e.display2();
e.check();
return 0;
}
Output:
Enter your valid information
Enter your age
144 • C++ Programming Fundamentals
21
Enter your Undergraduate Year
2024
Sorry, you cannot appear
Code Debriefing
QQ This code shows that the display function of our class exists in multiple
forms.
QQ Static binding is implemented here using function overloading.
QQ The functions all have the same name, but different signatures. That is,
they have different combinations and numbers of parameters.
QQ While calling the display function, keep in mind which signature calls
which function.
QQ Here, the compiler gets to know about the code attached to the function
call only at compile time.
};
class student : public person
{
public :
void display()//overridden
{
cout<<"Enter your Under Graduaate Year"<<endl;
}
};
int main()
{
person e;
Polymorphism • 145
student s;
cout<<"Please enter your information "<<endl;
s.display();
e.display();
return 0;
}
Output:
Please enter your information
Enter your undergraduate Year
Enter your age
Code Debriefing
QQ This code shows that the display function of our class exists in multiple
forms.
QQ Static binding is implemented using function overloading.
QQ The functions all have the same name, but different signatures. That is,
they have different combinations and numbers of parameters.
QQ While calling the display function, keep in mind which signature calls
which function.
QQ Here, the compiler gets to know about method attached to the function
call only at runtime.
a. No method of implementation is given; they only deal with the decla-
ration part.
b. I t is the responsibility of the class that implements an interface to
implement the methods, as well.
c. We cannot define variables inside our interface.
146 • C++ Programming Fundamentals
int main()
{
cout<<"\nInterfaces"<<endl;
child1 c1;
c1.Purely();
c1.method1();
return 0;
}
Output:
Interfaces
Parent method redefined
Parent class method
Code Debriefing
QQ Here, the interface concept is being applied.
QQ Static binding is implemented using function overloading.
QQ The method is redefined in the child class as it can inherit and modify
properties.
Polymorphism • 147
The following are few more terms and their definitions to make the interface
concept in C++ clearer.
};
class PublicChild1 : public parentc
{
public:
virtual int pro()
{
return (avgSal+9000);
}
};
{
return (avgSal+12000);
}
};
int main()
{
PublicChild1 obj1;
PublicChild2 obj2;
cout << "\nPublic child 1 average salary is "
<< obj1.pro() << endl;
cout << "\nPublichild2 average Salary is " << obj2.pro()
<< endl;
cout<< "\n";
return 0;
}
Output:
Public child 1 average salary is 239000
Publicchild2 average Salary is 242000
Code Debriefing
QQ In this code, the virtual function of our class exists in multiple forms.
QQ While calling the display function, keep in mind which signature calls
which function.
Code:
#include <iostream>
using namespace std;
class ABC
{
public:
virtual void Purely() = 0;
};
class child1: public ABC
{
public:
void Purely()
{
cout<<"\nParent method redefined by child1"<<endl;
}
Polymorphism • 149
};
class child2: public ABC
{
public:
void Purely()
{
cout<<"\nParent method redefined by child2"<<endl;
}
};
int main()
{
child1 c1;
child2 c2;
c1.Purely();
c2.Purely();
return 0;
}
Output:
Parent method redefined by child1
Parent method redefined by child2
The following examples showcase how functions in C++ are overloaded and
overridden.
int main()
{
cout<<"To show function Ooverloading "<<endl;
display(11);
display(11.11);
display("Eleven");
return 0;
}
Output:
To show function overloading
Integer is 11
Integer is 11
The number of characters is Eleven
Code Debriefing
QQ In this code, the display function of our class exists in multiple forms.
QQ Polymorphism is being implemented using function overloading.
QQ The functions all have the same name, but different signatures. That is,
they have different combinations and numbers of parameters.
QQ While calling the display function, keep in mind which signature calls
which function.
Polymorphism • 151
cout << "Addition method 1 = " << add(87, 45) << endl;
cout << "Addition method 2 = " << add(90.5, 63.6) << endl;
cout << "Addition method 3 = " << add(51, 5.6, 33) << endl;
return 0;
}
Output:
Addition method 1 = 132
Addition method 2 = 154.1
Addition method 3 = 89
Code Debriefing
QQ This code shows that the addition function of our class exists in multiple
forms.
QQ This type of polymorphism is implemented using function overloading
of the addition method.
QQ The functions all have the same name but different signatures. That is,
they have different combinations and numbers of parameters.
QQ While calling the display function, keep in mind which signature calls
which function.
Code:
#include <iostream>
using namespace std;
152 • C++ Programming Fundamentals
class person
{
public:
int age;
void display()
{
cout<<"Enter your age"<<endl;
cin>>age;
}
};
class student : public person
{
public :
int ugYear;
void display()
{
cout<<"Enter your Under GraduateYear"<<endl;
cin>>ugYear;
}
};
class exam: public student
{
public :
void check()
{
if((age>18) && (ugYear== 2021 || ugYear== 2022))
cout<<"You can appear for Common Admisiion Test
2022"<<endl;
else2
cout<<"Sorry you cannot appear for Common Admission
Test 2022"<<endl;
};
int main()
{
exam e;
Polymorphism • 153
Output:
To show function overriding
Please enter your information
Enter your Undergraduate Year
2023
Sorry you can not appear for Comman Admission Test 2022
Code Debriefing
QQ This code shows that the display function of our class exists in multiple
forms.
QQ This type of polymorphism is implemented using function overriding of
the display method.
QQ It is overridden in the child class, as it is inherited from the base class.
QQ The functions all have the same name but different signatures. That is,
they have different combinations and numbers of parameters.
QQ While calling the display function, keep in mind which signature calls
which function.
};
int myfriend(int a, int b)
{
return a+b;
}
int main()
{
int a,b;
cout<<"Enter numbers to add"<<endl;
cin>>a>>b;
cout<<"Addition gives "<<myfriend(a,b)<<endl;
return 0;
}
Output:
Enter numbers to add
23
567
Addition gives 590
Code Debriefing
QQ This code shows how the friend function is made.
QQ This function can be declared inside a class and defined outside the
class.
Polymorphism • 155
return 0;
}
Output:
Enter numbers to swap
23
67
After swapping A= 23 B=27
Swapping using the call by reference changes what is visible
After swapping A= 67 B=23
Swapping by using the call by pointers
int main()
{
Polymorphism • 157
int x;
float y;
cout<<"Enter the value of x and y "<<endl;
cin>>x>>y;
cout<<"Before Swapping";
cout<<"\nx1="<<x<<"\ty1="<<y;
swap(x,y);
cout<<"\nAfter Swapping";
cout<<"\nx1="<<x<<"\ty1="<<y;
return 0;
}
Output:
Enter the value of x and y
34
78
Before Swapping
x1=34 y1=78
After Swapping
x1=78 y1=34%
7.6 Namespaces
Namespaces in C++ logically organize of all our identifiers (variables,
methods, and classes) so they are defined and declared under one name or
a space. This creates a logical border between various elements and scope
created to access the namespace members. In our program, we can either
use already defined namespaces like std:: or define our own space using
the keyword namespace.
Features of Namespaces
QQ Namespaces created with the same name but different states or scope
can exist in C++.
QQ No access specifiers are required for namespace declarations.
QQ The nesting of namespaces is possible (a namespace within another
namespace).
QQ It is not a class, so no semicolon is used in the definition.
QQ Namespace declarations made will only be visible for a global scope.
158 • C++ Programming Fundamentals
namespace Ournamespace
{
// namespace body
} Ournamespace: : identifiers_any;
Code: Using Namespace
#include <iostream>
using namespace ;
namespace ourSpace1
{
void nFunc()
{
cout << "\nFunction of ourSpace1 called" << endl;
}
}
namespace ourSpace2
{
void nFunc()
{
cout << "\nFunction of ourSpace2 called" << endl;
}
}
int main ()
{
ourSpace1::nFunc();
ourSpace2::nFunc();
return 0;
}
Output:
Function of ourSpace1 called
Function of ourSpace called
Code Debriefing
QQ In this code, the namespaces are declared.
QQ Two functions are defined inside the namespaces.
QQ The function nFunc is called upon using the scope resolution operator.
Polymorphism • 159
Summary
QQ Polymorphism allows for multiple forms of a method with different
signatures but the same name.
QQ Methods made can exist in multiple forms by varying in type of
parameters and number of parameters they take in the signature of a
function.
QQ Dynamic or late binding tells which procedure will be called at runtime.
QQ Static or early binding tells which procedure will be called at compile
time.
QQ C++ provides interfaces that lead to no direct implementation and only
declare methods.
QQ A virtual function is a type of function that is declared as well as defined
in the parent or base class and redefined in the child class.
QQ A pure virtual function is a type of function that is only declared but
never implemented or redefined.
QQ The abstract class (ABC) is a type of class that has only pure virtual
functions. This means that it is only declared and never defined; this
helps all child classes to inherit and redefine the members as they wish,
too.
QQ Function overloading is done by giving functions the same name but
different signatures.
QQ Function overriding is done by giving functions the same name and
signatures.
QQ A friend function is a non-member function of a class that has access as a
normal function but is declared with the keyword friend.
QQ Generic functions in C++ act as a template and use different types of
parameters to give the desired results.
QQ Namespaces logically organize identifiers (variables, methods, and
classes) so they can be defined and declared under one name or a space.
160 • C++ Programming Fundamentals
Exercises
Theory Questions
1. What is polymorphism in C++? Describe the syntax for using it with
examples.
2. What are the different types of polymorphism available in C++?
3. What is the difference between compile time and runtime
polymorphism?
4. Discuss the concept of virtual and pure virtual functions in C++?
5. What do is meant by dynamic and static binding?
6. How is runtime polymorphism implemented in C++? Explain with
examples.
7. What are abstract classes? Explain few of their features.
8. What is the use of a friend function in C++? Explain a few of its
features.
9. What are templates in C++? Explain few of its features and how are
they are declared.
10. What are namespaces in C++? Explain few of their features.
11. Draw parallels between abstract and virtual functions in C++.
Practical Questions
1. Write a program in C++ to demonstrate the use of runtime polymorphism.
2. Write a program in C++ illustrating the use of pure virtual functions.
3. Write a program in C++ to depict the use of the abstract keyword.
4. Write a program in C++ to maintain an ecommerce database using
virtual functions.
5. Write a program in C++ to use the concept of templates to find the
average of five inputs.
6. Write a program in C++ to depict the use of an abstract base class.
7. Write a program in C++ to implement the concept of namespaces.
8. Write a program in C++ to show a student database using various
aspects of polymorphism.
Polymorphism • 161
MCQ-Based
1. Which of the following options correctly explains the concept of
polymorphism?
a. int func(float);
float func(int, int, char);
b. int func(int);
int func(int);
5. The language that supports classes but not polymorphism is called what?
a. child-class-based language
b. class-based language
c. object-based language
d. procedure-oriented language
b. Overloading &&
c. Overloading <<
d. Overloading +=
11. Two classes are derived from one base class and redefine a function
of the base class, also overloading some operators inside the body of
the class. Where should polymorphism be used, in the function or the
operator overloading?
a. Function overloading only
b. Operator overloading only
c. E
ither function overloading or operator overloading because polymor-
phism can be applied only once in a program
d. Both of these are using polymorphism
13. Which class or set of classes can illustrate polymorphism in the following
code?
abstract class student
{
public : int marks;
calc_grade();
}
class topper:public student
{
public : calc_grade()
{
return 10;
}
};
class average:public student
{
public : calc_grade()
164 • C++ Programming Fundamentals
{
return 20;
}
};
class failed{ int marks; };
{
public :
void disp()
{
cout<<"Its derived class";
}
}
void main() { student s; topper t;
s.disp();
t.disp();
}
a. its base class and then its derived class
b. its base class but not its derived class
c. its derived class and then its base class
d. None of the above
{
school s;
s.disp();
} }
MCQ
Answer Key
1. (c) 2. (e) 3. (c) 4. (b) 5. (c) 6. (b) 7. (b) 8. (b) 9. (b) 10. (c)
11. (c) 12. (d) 13. (b) 14. (a) 15. (d) 16. (a)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition)
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition) (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++ (BPB Publications September, 2020).
QQ Y. Kanetkar, Test Your C++ Skills (BPB Publications March, 2003).
Websites
QQ Learn CPP, accessed July 2022, https://www.learncpp.com
QQ Codes Cracker, accessed July 2022, https://codescracker.com
QQ Geeks For Geeks, accessed July 2022, https://www.geeksforgeeks.org
QQ Programiz, accessed July 2022, https://www.programiz.com
QQ Udacity, accessed July 2022, https://www.udacity.com
QQ Scaler, accessed July 2022, https://www.scaler.com
QQ C Plus Plus, accessed July 2022, https://cplusplus.com
QQ Silly Codes, accessed July 2022, https://sillycodes.com
CHAPTER
8
Operator Overloading
8.1 Basics
Polymorphism provides us with multiple forms of a method with different
signatures but the same name. Methods can exist in multiple forms by
varying the types of parameters and number of parameters they take in the
signature of a function. As discussed in the previous chapter, polymorphism
encompasses the overloading and overriding of functions and virtual
functions. In this chapter, we will consider another type of overloading:
operator overloading.
int m;
public:
opOverload()
{
}
void values()
{
cout<<"\nEnter any number\n";
cin>>m;
}
}
void display()
{
cout<<"\nFirst Number now is "<<m<<endl;
}
};
int main()
{
opOverload obj1;
obj1.values();
obj1++;
obj1.display();
return 0;
}
Output:
Entry any number
33
First number now is 34
Code Debriefing
QQ In this code, we have created a class with a few methods.
QQ The values() method is used to accept input for data members from
the user.
170 • C++ Programming Fundamentals
QQ Here, the unary operator ++ is being overloaded and used with one
object (obj1).
QQ This overloading takes no parameter, and the values stored in obj1 are
changed.
QQ The code now displays the changes made. The overloading was
performed successfully.
}
diff operator +=(diff obj1)
{
m= m+2;
cout<<"\nFirst number now is "<<m<<endl;
}
};
int main()
{
diff obj1,obj2;
obj1.display();
obj1==obj1;
obj1+=obj1;
return 0;
}
Operator Overloading • 171
Output:
Entry any numbers
23
56
Not Equal
class unary1
{
int m;
public:
unary1()
{
}
void values()
{
cout<<"\nEnter any numbers\n";
cin>>m;
}
void operator ++()
{
m++;
}
void display()
{
cout<<"\nFirst Number now is "<<m<<endl;
}
};
int main()
{
unary1 obj1,obj2;
obj1.values();
obj1++;
obj1.display();
return 0;
}
Output:
Enter any numbers
33
First Number now is 34
Operator Overloading • 173
Code Debriefing
QQ In this code, we created a class with a few methods.
QQ The values() method is used to accept input for data members from
the user.
QQ Here, the unary operator ++ is overloaded and used with an object
(obj1).
QQ This overloading takes no parameter and the values stored in obj1 get
changed.
QQ The code now displays the changes made. The overloading was
performed successfully.
unary2 ()
{
}
void values()
{
cout<<"\nEnter any number\n";
cin>>m;
}
}
void operator --()
{
m--;
}
174 • C++ Programming Fundamentals
void display()
{
cout<<"\nYour number now is "<<m<<endl;
}
};
int main()
{
unary2 obj1;
obj1.values();
++obj1;
obj1.display();
--obj1;
obj1.display();
return 0;
}
Output:
Enter any number
23
Your number now is 24
Your number now is 23
Code Debriefing
QQ In this code, we created a class with few methods.
QQ The values() method is used to accept input for data members from
the user.
QQ Here, the unary operators -- and ++ are being overloaded and used with
obj1.
QQ This overloading takes no parameter, and the values stored in obj1 are
changed.
QQ The code now displays the changes made. The overloading was
performed successfully.
and make them into polymorphic form. The syntax for binary operators is
as follows:
Return_DataType MyClass : : operator operationName(Parameters
list..)
{
// function body
}
Code: Overloading a Binary Operator
#include <iostream>
using namespace std;
class myclass
{
public:
int m,n;
void display()
{
cout<<"\nEnter any two numbers\n";
cin>>m>>n;
}
int operator - ()
{
return m-n;
}
};
int main()
{
myclass obj;
int r;
obj.display();
r= -obj;
cout<<"Difference is "<<r <<endl;
return 0;
}
Output:
Enter any two numbers
23
67
Difference is -44
176 • C++ Programming Fundamentals
Code Debriefing
In this code, we created a class with a few methods.
QQ The values() method is used to accept input for the data members
from the user.
QQ Here, the binary operator - is overloaded and used with obj.
QQ This overloading takes no parameter and returns with our result. The
values stored in the object (obj) are changed.
QQ The code now displays the changes made. The overloading was
performed successfully.
void values()
{
cout<<"\nEnter any number\n";
cin>>m;
}
myclass operator *(myclass &obj)
{
myclass t;
t.m= m* obj.m;
return t;
}
void display()
{
cout<<"\nYour Result is "<<m<<endl;
}
};
int main()
{
myclass obj1,obj2,r;
obj1.values();
Operator Overloading • 177
obj2.values();
r= obj1*obj2;
r.display();
return 0;
}
Output:
Enter any number
48
void input()
{
178 • C++ Programming Fundamentals
}
void display()
{
cout<<"String: "<<str;
}
concat operator +(concat s)
{
concat obj;
strcat(str,s.str);
strcpy(obj.str,str);
return obj;
}
};
int main()
{
concat str1,str2,str3;
str1.input();
str2.input();
str3=str1+str2;
str3.display();
return 0;
}
Output:
Enter your string: Hello
Code Debriefing
In this code, we created a class with a few methods.
QQ The input() method is used to accept data members from the user for
string data types.
QQ Here, the binary operator + is overloaded and helps concatenate the
entered strings.
Operator Overloading • 179
myclass obj3;
obj3.m = obj1.m + obj2.m;
obj3.n= obj1.n+obj2.n;
return obj3;
}
180 • C++ Programming Fundamentals
int main()
{
myclass obj1(86, 99);
myclass obj2(108, 245);
myclass obj3;
obj3= obj1+obj2;
cout << "\Sum is" << obj3.m<<endl;
cout << "Sum is "<< obj3.n<<endl;
return 0;
}
Output:
Sum is 194
Sum is 344
Code Debriefing
QQ In this code, we have created a class with a few constructors: one default
and the other parameterized.
QQ In this example, overloading is done using a function declared inside the
class and implemented outside the class.
QQ Here, the binary operator + is overloaded and used with obj1 and obj2.
The result is being stored in obj3.
QQ This overloading takes two parameters, and the values stored in the
objects are changed.
QQ The code now displays the changes made. The overloading was
performed successfully.
Summary
QQ Polymorphism provides us with multiple forms of a method with
different signatures but the same name.
QQ Operator overloading is a type of compile-time polymorphism in which
the basic operators we use can also be overloaded to give a functionality
to a user-defined data type.
QQ Operator overloading is done with two types of operators: unary and
binary.
Operator Overloading • 181
Exercises
Theory Questions
1. What is operator overloading? Explain the importance of operator
overloading.
2. List the operators that cannot be overloaded and justify why they cannot
be overloaded.
3. What is the operator function? Describe the operator function with
syntax and examples.
4. What are the limitations of overloading the unary increment/decrement
operator? How are they overcome?
5. Explain the syntax of unary operator overloading. How many arguments
are required in the definition of an overloaded unary operator?
6. Explain the syntax of binary operator overloading. How many arguments
are required in the definition of an overloaded binary operator?
Practical Questions
1. Write a program to overload the unary operator, say ++, for incrementing
the distance in a GPS system. Describe the working model of an
overloaded operator with the same program.
2. Write a program in C++ to overload the unary operator for processing
counters. It should support both upward and downward counting. It
must also support operators for adding two counters and storing the
result in another counter.
3. Write a program in C++ to overload arithmetic operators for
manipulating vectors.
182 • C++ Programming Fundamentals
c. 0
d. 3
7. Which of the following is the correct order for the process of operator
overloading?
i. Define the operator function to implement the required operations.
ii. Create a class that defines the data type that is to be used in the over-
loading operation.
iii. Declare the operator function op() in the public part of the class.
{ static int a;
public:
void show()
{ a++;
cout<<"a: "<<a<<endl;
}
};
int A::a = 5;
int main(int argc, char const *argv[])
{
A a;
return 0;
}
a. Error, as a private member a is referenced outside the class
b. Segmentation fault
c. No output
d. Program compiles successfully but gives a runtime error
MCQ
Answer Key
1. (b) 2. (d) 3. (d) 4. (b) 5. (c) 6. (c) 7. (b) 8. (c) 9. (c) 10. (a)
11. (b) 12. (d)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition)
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition) (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++ (BPB Publications September, 2020).
QQ Y. Kanetkar, Test Your C++ Skills (BPB Publications March, 2003).
Websites
QQ Learn CPP, accessed August 2022, https://www.learncpp.com
QQ Java Point, accessed August 2022, https://www.javatpoint.com
QQ Codes Cracker, accessed August 2022, https://codescracker.com
QQ Geeks For Geeks, accessed August 2022, https://www.geeksforgeeks.org
QQ C Plus Plus, accessed August 2022, https://cplusplus.com
QQ Silly Codes, accessed August 2022, https://sillycodes.com
CHAPTER
9
Structure and Union
Features of Structure
QQ Defined using the keyword struct and members access it using the
name.
QQ Memory allocation for a structure in C++ occurs contiguously.
QQ It has data members and functions that are similar to the variables and
functions used elsewhere in C++.
QQ Data members cannot be initialized inside a structure.
QQ Initialization of members can be done using curly braces.
QQ Accessing of members is done using the selector or dot operator.
188 • C++ Programming Fundamentals
The following programs in C++ use classes and help us observe the
difference between a class and a structure.
}
};
int main() {
Student s1("Rio");
Student s3(s1);
return 0;
}
Output:
Name is Rio
This is a member of a class
Structure and Union • 189
Code Debriefing
QQ In this code, we created a class with a few methods.
QQ The values’ methods are used to take input for the data members from
the user.
QQ Here, the constructor is overloaded and used with one object.
QQ The code displays the changes made. The overloading was performed
successfully.
};
int main()
{
Output:
The value is : 85
The value is : G
Size of structure : 9
Code Debriefing
QQ In this code, we create a structure with a few variables.
QQ The object of our structure is made to access the members.
QQ Observe that the size of the whole structure becomes different, as in a
class.
QQ The code displays the changes made.
190 • C++ Programming Fundamentals
};
int main()
{
struct OurStructure s1;
struct OurStructure s2 = { 240,'S' };
s1.x = 835;
s1.c = 'G';
cout << "The value is : "<< s1.x << endl;
cout << "The value is : "<< s1.c << endl;
cout<<"Size of structure : "<<sizeof(s1)<<endl;
cout << "The value is : "<< s2.x << endl;
cout << "The value is : "<< s2.c << endl;
cout<<"Size of structure : "<<sizeof(s2)<<endl;
return 0;
}
Output:
The value is : 835
The value is : G
Size of structure : 8
The value is : 240
The value is : S
Size of structure : 8
The value is : S
Size of structure structure : 8
Code Debriefing
QQ In this code, we create two structures with a few variables. A different
syntax is used for structure creation.
QQ The object of our structure is made to access the members.
QQ Observe that the size of the whole structure becomes different, as in a
class.
QQ The code displays the changes made.
};
int main()
{
return 0;
}
Output:
The value is : 240
The value is : S
Size of structure : 8
Code Debriefing
QQ In this code, we create two structures with a few variables. A different
syntax is used for structure creation.
QQ The object of our structure is made to access the members.
192 • C++ Programming Fundamentals
9.3 Union
Union that is another user-defined data type in C++. Union groups various
objects and members of different types and bytes together. Structure and
union may seem similar because of their syntax, but they vary in their
memory allocation to members. A union will give data variable memory
space that is equal to the space occupied by the data variable with the
largest size of that respective union.
The syntax for a union is as follows:
union UnionName
{//members
};
Features
QQ Defined using the keyword union and members accessed using under
the name
QQ Memory allocation for a union is determined by the largest member .
QQ It has data members and functions that are similar to the variables and
functions used elsewhere in C++.
QQ Data members can be initialized and overwritten if the value changes as
the same memory space is affected.
QQ Accessing of members is done using the selector or dot operator.
QQ A pointer to a structure in C++ is as follows: ->.
};
Structure and Union • 193
int main()
{
Ouput:
The value is : 72
The value is : H
Size of union : 4
Code Debriefing
QQ In this code, we create a union with a few variables.
QQ Then, the object of our union is made to access the members.
QQ Observe that the size of the whole union changes, as in a structure.
QQ The code displays the changes made.
Output::
The value is x : 8250
The value is c : H
Size of union : 12
The value is x : 595
The value is c : S
Size of union : 12
Code Debriefing
QQ In this code, we create a union with a few variables and assigned values
using the dot operator.
QQ Then, the object of our union is made to access the members.
QQ Observe that the size of the whole union changes, as in a structure.
QQ The code displays the changes made.
Structure Union
All data members can be initialized for a Only the first data member can be initialized
structure. for a union.
All data members can be accessed together Accessing of data members can be done only
for a structure. one at a time.
int i;
for (i = checo; i <= ocon; i++)
cout << i << " ";
return 0;
}
Output:
9 10 11 12 13
Code Debriefing
QQ In this code, we use enum with items.
QQ The for loop traverses the data structure and displays each member as
an index number.
QQ The index is +1, and this can be changed depending on the
requirements.
196 • C++ Programming Fundamentals
int main()
{
enum Gender { max, checo=9,lewis, kimi=18, mick, ocon };
int i;
for (i = checo; i <= ocon; i++)
cout << i << " ";
weekDays d;
d= Monday;
cout << "\n The Day of week is " << d+1<<endl;
return 0;
}
Ouput:
9 10 11 12 13 14 15 16 17 18 19 20
The Day of week is 2
Code Debriefing
QQ In this code, we use enum with items.
QQ The for loop traverses the data structure and displays each member as
an index number.
QQ The index is +1 and, this can be changed depending on the
requirements.
Features of Enumeration
QQ Defined using the keyword enum and elements are accessed using the
name
QQ Memory allocation for all members of enum is the same.
QQ It has data elements and a default position or value assigned that is
similar to an array.
QQ We can change the value of the elements, and the elements following
take up the value as defined.
Structure and Union • 197
Summary
QQ Structure is a user-defined data type in C++ that groups different data
types together.
QQ Union helps us to group various objects and members of different types
and bytes together.
QQ Memory allocation for a structure in C++ occurs contiguously.
QQ In a union, all data members share the memory space equal to the size
of the largest member.
QQ All data members can be initialized for a structure.
QQ Only the first data member can be initialized for a union.
QQ enum or enumeration is a unique data type in C++ that allows us to
define data types and named elements of our choice by assigning names
to integer constants.
QQ Enum elements are called enumerators.
Exercises
Theory Questions
1. What are structures? Justify their need with an example.
2. Why are structures are called heterogeneous data types?
3. Explain storage organization of structure variables.
4. Write a short note on passing structure type variables to a function,
and the suitability of different parameter passing schemes in different
situations.
5. What are unions? Write a program to illustrate the use of a union.
6. What are the differences between structures and unions?
7. Define enum and its purpose.
198 • C++ Programming Fundamentals
Practical Questions
1. Write a program in C++ for processing admission reports. Use a structure
that has elements representing information such as roll number, name,
date of birth (use a nested structure), and branch allotted. The functions
processing the members of a structure must be a part of a structure. The
format of the report is as follows:
Roll.no. Name Date of Birth Branch Allotted
XX xxx dd/mm/yy xxxxxxxxxxx
} S;
int main()
{
cout << S.A << " " << S.B;
return 0;
}
a. 0 2
b. 0 0
c. 2 0
d. Error
typedef struct{
int A;
char* STR;
} S;
int main()
{
200 • C++ Programming Fundamentals
S ob = { 10, "india" };
S* ptr;
ptr = &ob;
char CH;
};
int main()
{
struct st s[] = { { 10, 'A' }, { 20, 'B' } };
int X, Y;
X = s[0].A + s[0].CH;
Y = s.A + s.CH;
cout << (X * Y);
return 0;
}
a. 6450
b. 1020
c. 9765
d. Error
} SS;
int main()
{
struct st1* PTR = &SS;
int X = 0;
X = PTR->A + PTR->S.ch;
cout << X;
return 0;
}
a. 65
b. 75
c. 97
d. 107
return 0;
}
Structure and Union • 203
a. 123
john
b. john
john
c. compile time error
d. runtime error
}
a. 19845
b. 20000
c. 15000
d. 19844
14. Which operator connects the structure name to its member name?
a. -
b. ->
c. .
d. Both . and ->
16. What is the correct syntax to declare a function foo() that receives an
array of structures in a function?
a. void foo(struct *var);
b. void foo(struct *var[]);
c. void foo(struct var);
d. None of the above
18. The data elements in the structure are also known as what?
a. objects
b. members
c. data
d. objects and data
206 • C++ Programming Fundamentals
22. The size of the following union, where int occupies 4 bytes of memory is
_____________.
union demo
{
float x;
int y;
char z[10];
};
a. 8 bytes
b. 4 bytes
c. 10 bytes
d. 18 bytes
c. Both a & b
d. None of the above
26. Sizeof a union gives the size of the longest element in the union.
a. Yes
b. No
c. May be possible in some situations
d. Cannot give an answer
a. 3 and 4
b. 1 and 2
c. 2 and 3
d. All of the above
30. Which operator connects the structure name to its member name?
a. -
b. .
c. Both (b and (c)
d. None of the above
c. b-var;
d. b>var;
int main()
{
test.x = 10;
test.y = 'A';
printf("%d %c", test.x,test.y);
return 0;
}
a. 0.416666666666667
b. garbage value garbage value
c. Compilation Error
d. None of the above
b. 8
c. 10
d. 9
struct
{
int i;
Structure and Union • 213
float ft;
}decl;
int main(){
decl.i = 4;
decl.ft = 7.96623;
printf("%d %.2f", decl.i, decl.ft);
return 0;
}
a. 4 7.97
b. 4 7.96623
c. Compilation error
d. None of the above
MCQ
Answer Key
1. (a) 2. (a) 3. (a) 4. (b) 5. (a) 6. (b) 7. (b) 8. (a) 9. (a) 10. (a)
11. (d) 12. (a) 13. (b) 14. (c) 15. (a) 16. (a) 17. (b) 18. (b) 19. (c) 20. (a)
21. (a) 22. (c) 23. (c) 24. (b) 25. (c) 26. (a) 27. (b) 28. (b) 29. (d) 30. (b)
31. (b) 32. (b) 33. (a) 34. (d) 35. (b) 36. (b) 37. (b) 38. (a) 39. (a) 40. (c)
41. (d) 42. (a) 43. (d) 44. (a) 45. (b) 46. (c)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition)
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition) (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++ (BPB Publications September, 2020).
QQ Y. Kanetkar, Test Your C++ Skills (BPB Publications March, 2003)
Websites
QQ Learn CPP, accessed August 2022, https://www.learncpp.com
QQ Codes Cracker, accessed August 2022, https://codescracker.com
QQ Geeks For Geeks, accessed August 2022, https://www.geeksforgeeks.org
QQ Udacity, accessed August 2022, https://www.udacity.com
QQ Scaler, accessed August 2022, https://www.scaler.com
QQ C Plus Plus, accessed August 2022, https://cplusplus.com
QQ Silly Codes, accessed August 2022, https://sillycodes.com
CHAPTER
10
Exception Handling
1. Synchronous: This type of exception can only arise from the throw
statements. For example, accessing an index element that the array might
not have termed an array index generates an out of bounds exception.
2. Asynchronous: This type of exception includes keyboard or input
interrupts while a program is being executed and disrupts the natural
flow of the C++ code. These exceptions are not handled directly but are
managed using the signal concept.
Code: Exception Handling (1)
#include <iostream>
using namespace std;
int main()
{
int x = 0;
int y=10;
cout << "oops wrong \n"<<y/x<<endl;
}
Output:
oops wrong
zsh: floating point exception
Code: Exception Handling (2)
#include <iostream>
using namespace std;
class Parent {
public:
int p=60;
void showP()
{
cout<<"\nParent's age is " <<p<< endl;
};
public:
int c=20;
void showC() {
cout<< "\nChild's age is " <<c<< endl;
public:
int g=4;
void showg() {
cout<< "\nGrandchild's age is " <<g<< endl;
;
}
};
int main() {
Grandchild g1;
g1.showP();
g1.showC();
g1.showg();
return 0;
}
c
Output:
inherit.cpp:25:2: error: expected ‘;’ after class
}//syntax error will ocur as clas declaring syntax not followed
Code Debriefing
QQ As you can observe from this code, we did not follow the syntax rules in
C++.
QQ This results in a syntax error message given by the compiler.
QQ It shows us the line at which error occurred and why the error led to
program termination.
218 • C++ Programming Fundamentals
10.2 Exception Handling
In C++, exceptions are handled using a try-catch block, where we can
throw a particular exception we feel our code might face and handle it in
the block. Let us now get familiar with important keywords we will be using
throughout the exception handling mechanism.
QQ Try: This block is used to throw our exception. We can try for conditions
and if the conditions are met (true), we throw an exception. A try block
is always followed by a catch block.
QQ Catch: This block is used when an exception is thrown. It gives what
happens after catching the exception and managing it with an exception
handler. One try block can be followed by multiple catches.
QQ Throw: This keyword simply throws an exception and does nothing
much beyond that. It is the responsibility of the try-catch block to
handle the exception.
The syntax for the try-catch block is as follows:
try {
// code
throw exceptionName;
}
catch () {
// code
}
Code: Handling Exceptions Using Try-Catch Blocks
#include <iostream>
using namespace std;
int main()
{
int x = 0;
int y=10;
//cout << "oops wrong \n"<<y/x<<endl;
try {
if (y > 9)
{
throw y;
}
}
Exception Handling • 219
catch (int y ) {
cout << "\n The Exception thrown has been Caught \n";
}
return 0;
}
Output:
The Exception thrown has been Caught
Code Debriefing
QQ As you can observe from this code, we use the try-catch block
mechanism to handle the exception.
QQ The try block is inside main. If the statement is satisfied, we throw our
exception in the try block.
QQ The catch block does its work and catches the exception, then prints the
message.
int main()
{
int x = -9;
int y=10;
//cout << "oops wrong \n"<<y/x<<endl;
try {
if (y > 9)
{
throw y;
}
if (x< 0)
{
throw x;
}
}
catch (int y ) {
cout << "\nThe Exception thrown has been Caught \n";
}
220 • C++ Programming Fundamentals
catch (int x ) {
cout << "\nThe Exception thrown has been Caught \n";
}
return 0;
}
Output:
Code Debriefing
QQ As you can observe from this code, we use the try-catch block
mechanism to handle exceptions.
QQ Inside main, we have a try block. If the statement is satisfied, we throw
our exception in the try block.
QQ The catch block works in a similar way to a switch case and checks for
relevant parameters thrown towards it.
QQ This code does its work to catch the exception and prints a message.
class trial {
};
int main()
{
try {
throw trial();
}
Output:
Caught an exception of a class
Code Debriefing
QQ As you can observe from this code, we created our own exception in
C++ using the class trial.
QQ Inside main, we throw our exception to the class trial constructors within
the try block.
QQ The catch block does its work and catches the exception, and then it
prints the message.
QQ As our exception is a class, we called its data method using the object.
int main()
{
try
{
throw ourException();
}
catch(ourException& oE)
{
cout<< "\nOur custom exception has been caught" <<endl;
cout<< "Calling function "<<oE.func1() <<endl;
}
catch(std::exception& oE) {
}
return 0;
}
Exception Handling • 223
Output:
Our custom exception has been caught
Calling function
User, Please enter an Exception
Code Debriefing
QQ As you can observe from this code, we created our own exception by
inheriting properties from the exception parent class.
QQ Inside main, we throw our exception in the try block.
QQ The catch block does its work and catches the exception, and then it
prints a message.
QQ As our exception is a class, we called its data method using the object.
Summary
QQ An exception in programming is an abnormal condition at runtime that
leads to either program termination or faulty execution.
QQ Errors are illegal statements or functionalities the programmer might
have used in their program.
QQ Errors are beyond repair, but exceptions can be handled.
QQ Exceptions are handled using a try-catch block where we can throw a
particular exception.
QQ A try block is used to throw an exception. We can check for conditions,
and if they are met, the program throws an exception.
QQ A catch block is used when an exception is thrown. What happens after
catching the exception occurs in this block.
QQ A try block is always followed by a catch block, and one try block can
be followed by multiple catches.
QQ There are standard exceptions programmers might face often, and these
are part of the std library.
QQ In C++ custom exceptions, we can inherit properties from the standard
exception class and override its methods.
224 • C++ Programming Fundamentals
Exercises
Theory Questions
1. What are exceptions? What are the differences between synchronous
and asynchronous exceptions?
2. Explain the exception handling model of C++ with various constructs
supported by it.
3. What is the syntax for indicating a list of exceptions that a function can
raise? What happens if an unspecified exception is raised?
4. What happens when an exception is raised in a try block having a few
constructed objects?
5. What happens when a raised exception is not caught by a catch block?
6. List the ten rules for handling exceptions successfully.
Practical Questions
1. Write a program to demonstrate the catching of all exceptions.
2. Write a program in C++ to compute the square root of a number. The
input value must be tested for validity. If it is negative, should the user-
defined function my_sqrt()raise an exception?
3. Write a program in C++ that transfers the control to a user-defined
terminate function when a raised exception is uncaught.
4. Write a program in C++ that installs the user-defined unexpected
function to handle exceptions.
5. Write a program in C++ that divides two complex numbers. Overload
the divide (/) operator. Can this program handle cases such as division-
by-zero using exceptions?
6. Write a program in C++ for matrix multiplication. The matrix
multiplication function should notify the user if the order of the matrix
is invalid using exceptions.
7. Write a program in C++ to add two vectors. Each vector object, an
instance of the class Vector, has the dynamic allocation of their data
members. Can this program catch exceptions raised by new operators
and take corrective actions?
Exception Handling • 225
MCQ-Based
1. What is an exception in a C++ program?
a. A problem that arises during the execution of a program
b.A problem that arises during compilation
c. A syntax error
d. A semantic error
10. Which of the following statements are correct about the catch handler?
i. It must be placed immediately after the try block.
ii. It can have more than one parameter.
iii. There must be one, and only one, catch handler for every try block.
iv. There can be multiple catch handlers for a try block.
v. General catch handlers can be kept anywhere after the try block.
Exception Handling • 227
a. i, iv, v
b. i, ii, iii
c. i, iv
d. i, ii
11. In a nested try-catch block, if the inner catch block gets executed, then
the _________
a. program stops immediately
b. outer catch block also executes
c. c ompiler jumps to the outer catch block and executes the remaining
statements of the main() function
d. c ompiler executes the remaining statements of the outer try-catch
block and then the main() function
12. If the inner catch block is unable to handle the exception thrown, then
_________
a. the compiler looks for the outer try-catch block
b. the program stops abnormally
c. t he compiler will check for the appropriate catch handler of the outer
try block
d. t he compiler will not check for the appropriate catch handler of the
outer try block
13. In nested try-catch blocks, if both the inner and outer catch blocks are
unable to handle the exception thrown, then the _________
a. compiler executes only main()
b. compiler throws a compile-time error
c. program will run without any interruption
d. program will be terminated abnormally
c. terminate()
d. abandon()
15. How one can restrict a function to throw particular exceptions only?
a. By defining multiple try-catch blocks inside a function
b. By defining a generic function within a try-catch block
c. By defining a function with throw clauses
d. Not allowed in C++
16. Which function is invoked when we try to throw an exception that is not
supported by a function?
a. indeterminate()
b. unutilized()
c. unexpected()
d. unpredicted()
c. i, ii
d. ii, iii
20. What are the disadvantages if we use the return keyword to return error
codes?
a. You have to handle all exceptional cases explicitly.
b. Your code size increases dramatically.
c. The code becomes more difficult to read.
d. All of the above
21. In a nested try-catch block, if the inner catch block gets executed, then
the _________
a. program stops immediately
b. outer catch block also executes
c. c ompiler jumps to the outer catch block and executes remaining state-
ments of the main() function
d. c ompiler executes the remaining statements of the outer try-catch
block and then the main() function
23. If the inner catch block is unable to handle the exception thrown, then
the _________.
a. program stops abnormally
b. the compiler looks for the outer try-catch block
c. t he compiler will check for appropriate catch handler of the outer try
block
d. t he compiler will not check for the appropriate catch handler of the
outer try block
24. Irrespective of the exception occurrence, the catch handler will always
get executed.
a. True
b. False
d. Inside try
Exception Caught
After throw
After catch
31. What is the output of this program?
#include<iostream>
using namespace std;
int main ()
{
try {
int* myarray = new int[1000];
cout << "Allocated";
}
catch (exception& LFC){
cout << "Standard exception: " << LFC.what() << endl;
}
return 0;
}
a. Error
b. Allocated
c. Standard exception
d. Depends on the memory
{
cout << "Outer Catch\n";
}
return 0;
}
a. Inner Catch
b. Outer Catch
c. Inner Catch
Outer Catch
d. Error
if (b == 0)
throw "Division by zero not allowed";
res = a / b;
cout << res;
}
a. 0
b. Bad operator
c. 10
d. 15
public:
virtual void myvirtualfunc() const {}
};
class mytriangle: public shape
{
public:
virtual void myvirtualfunc() const
{
};
};
int main()
{
shape shape_instance;
shape &ref_shape = shape_instance;
try
{
mytriangle &ref_mytriangle = dynamic_cast<mytriangle&>
(ref_shape);
}
catch (bad_cast)
{
cout << "Caught: bad_cast exception\n";
}
return 0;
}
a. Caught standard exception
b. No exception arises
c. Caught: bad_cast exception
d. Caught: cast
if (B == 0)
throw 2;
C = A / B;
}
catch (int num) {
cout << "Error code: " << num << endl;
}
return 0;
}
a. Error code: 2
b. Syntax error
c. No output
d. Garbage value
240 • C++ Programming Fundamentals
if (B == 0)
throw "divide by zero";
C = A / B;
}
catch (char* e) {
cout << "Exception Received: " << e << endl;
}
return 0;
}
Exception Handling • 241
int main()
{
try {
int A = 10;
int B = 0;
int C;
if (B == 0)
throw "divide by zero";
C = A / B;
}
catch (const char* e) {
cout << "Exception Received: " << e << endl;
}
return 0;
}
a. Exception received: divide by zero
b. Syntax error
c. No output
d. Program crashed at runtime
if (B == 0)
throw "Divide by zero";
C = A / B;
}
catch (int num) {
cout << "Error Code: " << num << endl;
}
catch (...) {
cout << "Exception received" << endl;
}
return 0;
}
a. Exception received
b. Divide by zero
c. Syntax error
d. No output
int main()
{
try {
int A = 10;
int B = 0;
int C;
if (B == 0) {
Exception E;
throw E;
}
C = A / B;
}
catch (exception E) {
cout << "Exception Received" << endl;
}
return 0;
}
Exception Handling • 243
a. Exception received
b. Divide by zero
c. Syntax error
d. No output
if (B == 0) {
exception E;
throw E;
}
C = A / B;
}
catch (exception E) {
cout << "Exception Received" << endl;
}
return 0;
}
a. Exception Received
b. Divide by zero
c. Syntax error
d. No output
int main()
{
try {
int A = 10;
244 • C++ Programming Fundamentals
int B = 0;
int C;
if (B == 0) {
bad_exception E;
throw E;
}
C = A / B;
}
catch (bad_exception E) {
cout << "Exception Received" << endl;
}
return 0;
}
a. Exception Received
b. Divide by zero
c. Syntax error
d. No output
return 0;
}
a. ###Exception Received
b. @@@Exception Received
c. Syntax error
d. No output
int main()
{
try {
int A = 10;
int B = 0;
int C;
if (B == 0) {
bad_exception E;
throw E;
}
C = A / B;
}
catch (bad_exception E) {
cout << "@@@Exception Received" << endl;
}
catch (exception E) {
cout << "###Exception Received" << endl;
}
return 0;
}
a. ###Exception Received
b. @@@Exception Received
c. Syntax error
d. No output
246 • C++ Programming Fundamentals
MCQ
Answer Key
1. (a) 2. (b) 3. (a) 4. (a) 5. (b) 6. (a) 7. (d) 8. (a) 9. (b) 10. (c)
11. (d) 12. (c) 13. (d) 14. (c) 15. (c) 16. (c) 17. (b) 18. (b) 19. (c) 20. (d)
21. (d) 22. (b) 23. (c) 24. (c) 25. (c) 26. (d) 27. (a) 28. (a) 29. (b) 30. (a)
31. (b) 32. (a) 33. (b) 34. (a) 35. (a) 36. (c) 37. (b) 38. (d) 39. (a) 40. (a)
41. (b) 42. (a) 43. (d) 44. (d) 45. (a) 46. (a) 47. (c) 48. (a) 49. (a) 50. (a)
51. (b)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition)
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition) (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++ (BPB Publications September, 2020).
QQ Y. Kanetkar, Test Your C++ Skills (BPB Publications March, 2003).
Websites
QQ Learn CPP, accessed August 2022, https://www.learncpp.com
QQ Codes Cracker, accessed August 2022, https://codescracker.com
QQ Roll Bar, accessed August 2022, https://rollbar.com
QQ Geeks For Geeks, accessed August 2022, https://www.geeksforgeeks.org
QQ Udacity, accessed August 2022, https://www.udacity.com
QQ Scaler, accessed August 2022, https://www.scaler.com
QQ C Plus Plus, accessed August 2022, https://cplusplus.com
QQ Silly Codes, accessed August 2022, https://sillycodes.com
CHAPTER
11
File Handling
Files
Files created in C++ help to store data onto the hard disk and remain in
the system for later use. This is different from traditional programs, where
our data or objects holding data get deleted after program termination to
reclaim the temporary memory space allotted. Many times, we need our
data to be securely stored in the system so fetching items out of a file
requires less time.
Streams
For the user to enter and provide details or values, we use input streams. A
stream refers to a group of bytes that can be accessed sequentially. There
are two different types of streams. Input streams are used to hold the
input from a user, such as a keyboard. For example, the user might press
any key on the keyboard, even when not asked for it. In a situation like
248 • C++ Programming Fundamentals
this, all these keys are saved in the input stream and used later when the
program itself requires it, saving the user energy and your code from any
fault or error. The second type is an output stream, which is used for the
output to a monitor, file, or printer. For example, let’s suppose you need
a printout, but the printer is currently working on another document, so
your data/file waits for its turn to be given as output. To able to use all these
functionalities in your C++ code, you need to include the iostream header
file, which provides the program with a whole hierarchy of classes (multiple
inheritance) to make use of all I/O classes.
Although the iostream class is derived from ios_base, iostream is the
one you will be working directly with. The symbols << or >> are not to
be confused with “greater than” or “less than.” In C++, these are special
operators you will add to your programs in your coding journey.
QQ The iostream class can handle both input and output streams, be it the
user pressing random keys or an alert message to the user not to do so,
all done through one class. It is the base class for all the other I/O stream
classes we will be using throughout this chapter.
QQ The istream class is for input streams, and this class is derived from the
iostream class. The extraction operator (>>) removes values from the
stream created when the user presses keys (whether asked to or not). It
also has functions for input operations like get() and getline().
QQ The ostream class is for output streams and this class is derived from
the iostream class. The insertion operator (<<) is used to put values in
the stream to be displayed on output devices like monitors. It also has
functions for input operations like put() and write().
QQ The fstream class can handle both input and output operations related
to files opening and closing, such as reading particular items of a file or
writing onto a file. It has various functions with special operability.
QQ The ifstream handles all the file input-related operations and has
various functions with special operability, like get(), getline(),
read(), seekg(), and tellg().
QQ The ofstream class can handle input operations related to writing onto a
file. It has various functions with special operability like put(), write(),
seekp(), and tellp().
QQ The streambuf class is used to manage the input and output streams
through a pointer, which points to the buffer.
File Handling • 249
Output:
We are learning and improving everyday.
We are learning and improving everyday.
-1
Code Debriefing
QQ In this code, we used the ofstream class and created its object and a
string value.
QQ We then used the open method to access our file in open mode.
QQ Text entered is written onto the file using the ifstream class object.
250 • C++ Programming Fundamentals
QQ The program then prints the content of the newly written file.
QQ The close method is called upon to close the file we had opened earlier.
11.2 File Operations
The major steps needed in C++ for file handling are as follows:
Opening a file: This is the first step taken toward file management in C++
and can be done either by passing our file name in the constructor when an
object is created or using the open() method.
The syntax for opening a file is as follows:
void open(const char* ourFileName, ios::openMode mode);
or
open() function
Output:
Our new file has been created%
Code Debriefing
QQ In this code, we used the fstream class and created its object.
QQ We used the open method to access our file in open mode.
QQ The program then prints the message “Our new file has been created.”
QQ The close method is called upon to close the file we opened earlier.
{
ofstream ofObj;
string ourLine;
ofObj.open("textFile3.txt");
while (ofObj)
{
getline(cin, ourLine);
if (ourLine == "-1")
break;
cout<< ourLine << endl;
}
ofObj.close();
ifstream ifObj;
ifObj.open("textFile3.txt");
while (ifObj)
{
getline(ifObj, ourLine);
cout << ourLine << endl;
}
ifObj.close();
return 0;
}
Output:
We are learning and improving everyday.
We are learning and improving everyday.
-1
Code Debriefing
QQ In this code, we used the ofstream class and created its object and a
string value.
QQ We then used the open method to access our file in open mode.
QQ Text entered is written onto the file using the ifstream class object.
QQ The program then prints the content of the newly written file.
QQ The close method is called upon to close the file we had opened earlier.
File Handling • 253
Both of the above functions take up two parameter offsets that tell how far
the pointer has to move in terms of bytes. The iostream flag tells where the
new start is.
The syntax for randomly accessing a file is as follows:
fileObject seekg(offset number);
fileObject seekp(offset number);
string ourItem;
ifObj.seekg(3);
getline(ifObj, ourItem);
cout << ourItem << '\n';
ifObj.seekg(6, std::ios::cur);
getline(ifObj, ourItem);
cout <<ourItem << '\n';
ifObj.seekg(-10, std::ios::end);
getline(ifObj,ourItem);
cout << ourItem << '\n';
return 0;
}
Output:
Code Debriefing
QQ In this code, we used the ifstream class and created its object and a
string value.
QQ We then used the open method to access our file in open mode.
QQ The Seekg method is used to print the content of the newly written file.
QQ The getline method helps to print the items of our file line by line, and
it takes two parameters.
Object Serialization
Serialization in C++ programming is the mechanism of converting an object
in our code into a sequence of bytes (also called the stream of data or the
object). This stream can be stored easily and even used for communicating
between systems and sharing information contained in the sequence of
bytes. Deserialization is done to reverse the process of serialization, where
the bytes are converted back to the objects and normal data.
File Handling • 255
Summary
QQ Files created in our C++ program help to store data onto the hard disk
and remain in the system for later use.
QQ In C++, for the user to enter and provide details or values, we use input
streams. A stream references a group of bytes that can be accessed
sequentially.
QQ Input streams are used to hold the input from a user, such as a
keyboard.
QQ Output streams are used to showcase output by a monitor, file, or
printer.
QQ In C++ code, you need to include the iostream header file, which
provides the program with a whole hierarchy of classes (multiple
inheritance) to make use of all I/O classes.
QQ The iostream class can handle both input and output streams, even if it
is a user pressing random keys.
QQ The fstream class can handle both input and output operations related
to files opening and closing, like reading.
QQ Opening a file is the first step taken toward file management in C++.
It can be done either by passing a file name in the constructor when an
object is created or using the open() method.
QQ Writing to a file is done using the ofstream or fstream classes to enter
data onto created or opened files.
QQ Reading a file is done using the ifstream or fstream classes to fetch
data from created or opened files.
QQ Closing a file is the last, important step in file handling.
QQ At program termination, memory is freed automatically. However, as to
not take any chances to have an item leak, we should always close our
files.
QQ Random file access means the control is not given by default to the start
or the end of the file, but at any point in the file. This is done using
special file operations that assign the file pointer to the point we wish to
access.
256 • C++ Programming Fundamentals
QQ The Seekg() function is used for input, and g represents get. It will
change the pointer position to read.
QQ The Seekp() function is used for output, and p represents post. It will
change the pointer position to write.
QQ Serialization is the mechanism of converting an object into a sequence
of bytes (also called a stream of data).
QQ Deserialization is also done to reverse the process of serialization, where
the bytes are converted back to the objects and normal data.</UL>
Exercises
Theory Questions
1. What is file handling in C++? Discuss its various aspects.
2. What streams are required while handling files?
3. Discuss seek functions and its form in C++.
4. How is random access carried out in a file?
5. Explain the various modes of opening writing and reading a file?
6. What is serialization in C++? How is it carried out?
7. What is deserialization in C++? How is it carried out?
Practical Questions
1. Write a C++ program to maintain a book record using file handling.
2. Write a C++ program to maintain house records using file handling.
3. Write a C++ program for the registration (signup) process using file
handling.
4. Write a C++ program to read and write file operations in file handling.
5. Write a C++ menu-driven program to perform the following actions:
add, modify, append, and display.
6. Write a C++ program to store or enter data to a file using file handling.
7. Write a C++ program to retrieve information from the file using file
handling.
File Handling • 257
8. Write a C++ program to read and display a file using file handling.
9. Write a C++ program to merge two files into a third file using file
handling.
10. Write a C++ program to encrypt files using file handling.
11. Write a C++ program to decrypt files using file handling.
12. Write a C++ program to read and write values through an object using
file handling.
13. Write a C++ program to count digits, letters, and spaces using file han-
dling.
14. Write a C++ program to count words, lines, and total size using file
handling.
15. Write a C++ program to read a text file and write it in another text file
using file handling.
16. Write a C++ program to count the occurrence of a word using file han-
dling.
17. Write a C++ program to read and write student details using file han-
dling.
18. Write a C++ program to manipulate file pointers using file handling.
MCQ-Based
1. By default, all the files are opened in _________ mode.
a. Binary
b. Text
c. Cannot be determined
2. It is not possible to combine two or more file opening modes in the open
() method.
a. True
b. False
b. ios::nocreate
c. ios::noreplace
d. ios::truncate
5. If we have an object from the ofstream class, then the default mode of
opening the file is _________.
a. ios::in
b. ios::out
c. ios::in|ios::trunc
d. ios::out|ios::trunk
7. If we have an object from the fstream class, then what is the default
mode of opening the file?
a. ios::in|ios::out
b. ios::in|ios::out|ios::trunc
c. ios::in|ios::trunc
d. Default mode depends on the compiler
c. iostream
d. None of these
9. Streams that will be performing both input and output operations must
be declared as class _________.
a. iostream
b. fstream
c. stdstream
d. Stdiostream
10. To perform file I/O operations, we must use the _________ header file.
a. < ifstream>
b. < ofstream>
c. < fstream>
d. Any of these
12. Which of the following is used to move the file pointer to the start of a
file?
a. ios::cur
b. ios::start
c. ios::first
d. ios::beg
c. ios::in
d. ios::ate
17. Which of the following methods can be used to open a file in file han-
dling?
a. Using open( )
b. Constructor method
c. Destructor method
d. Both A and B
c. <
d. None of the above
ofstream of ("find.txt");
pbuf = of.rdbuf();
do { i = cin.get();
p -> sputc(i);
} while (i != '.');
of.close();
return 0; }
a. insertion operator
b. $ symbol
c. dot operator
d. none of the above
30. In fopen(), the open mode “wx” is sometimes preferred over “w”
because
i. Use of wx is more efficient.
ii. If w is used, the old contents of the file are erased and a new empty
file is created. When wx is used, fopen() returns NULL if the file
already exists.
a. Only i
b. Only ii
c. Both i and ii
d. None of the above
34. Which function is used to return to the first position back from the end
of a file object?
a. Seekg
b. Seekp
c. Both seekg and seekp
d. None of the above
36. How can we get to the position at the nth byte of fileObject?
a. fileObject.seekg( 'filename',n );
b. fileObject.seekg( n, 'filename' );
c. fileObject.seekg( n );
d. fileObject.seekg( n, ios::app );
MCQ
Answer Key
1. (b) 2. (b) 3. (d) 4. (a) 5. (d) 6. (b) 7. (d) 8. (a) 9. (b) 10. (c)
11. (b) 12. (d) 13. (a) 14. (a) 15. (c) 16. (a) 17. (d) 18. (b) 19. (b) 20. (d)
21. (c) 22. (c) 23. (c) 24. (a) 25. (b) 26. (d) 27. (d) 28. (d) 29. (d) 30. (b)
31. (a) 32. (c) 33. (a) 34. (a) 35. (d) 36. (c) 37. (c)
References
Books
QQ B. Stroustrup, The C++ Programming Language (4th Edition)
(Addison-Wesley Professional, 2013).
QQ K. R. Venugopal, Mastering C++ (2nd Edition) (McGraw Hill
Education, July 2017).
QQ Y. Kanetkar, Let Us C++ (BPB Publications September, 2020).
QQ Y. Kanetkar, Test Your C++ Skills (BPB Publications March, 2003).
Websites
QQ Learn CPP, accessed August 2022, https://www.learncpp.com
QQ Codes Cracker, accessed August 2022, https://codescracker.com
QQ Geeks For Geeks, accessed August 2022, https://www.geeksforgeeks.org
QQ Udacity, accessed August 2022, https://www.udacity.com
QQ Scaler, accessed August 2022, https://www.scaler.com
QQ C Plus Plus, accessed August 2022, https://cplusplus.com
QQ Silly Codes, accessed August 2022, https://sillycodes.com
Index
Symbols Use, 2
Catch, 218
(~) tilde, 84
C & C++ differences, 37–38
A Character, 9
Characteristics
Abstraction, 5
Destructors, 84–85
Access specifiers, 99–100
Static keyword, 89
American National Standard Institute
Character literals, 19
(ANSI), 2
Class, 4
Arrays and Strings, 43–58
Base, 6, 97
Multi-Dimensional, 51, 51–52
Child, 98
Operations, 45–50
Derived, 6, 98
Assembly code, 11
Fstream, 248
Asynchronous, 216
Ifstream, 248
B Instance, 4
Base address, 59 Iostream, 21, 248
Basic Play in C++, 19–42 Istream, 21, 248
Comments, 22–23 Ofstream, 248
Conversion, 25–27 Ostream, 21, 248
DefiningFunctions, 36–37 Parent, 97
Literals, constants, and qaualifiers, 19–20 Streambuf, 248
Loops, 28–32 Sub, 98
Operators and types, 23–25 Super, 97
Stream-Based IO, 20–22 Classes in C++, 77–96
Binary operators, 24 Class methods, 87–89
Boolean, 9 Making, 77–78
Code reusability, 125
C Compiler, 11
C++ Conditional statement, 32
delete, 90 Constant, 19
New, 90 Constructor
C++ and Beyond, 1–18 Default, 79–80
Basics, 7 Parameterized, 82
Execution flow, 11 Constructor calling, 124–125
Origin of, 1–2
270 • Index
Throw, 218 V
Traversing, 48
Variables, 7
Traversing 1D array, 45
declaration, 7
Try, 218
definition, 7
Typecasting, 63
Various programming paradigms
Type conversion, 25
Object oriented, 4
U Procedural, 4
Structural programming, 3–4
Unary operators, 23, 171
Virtual function, 147
Union, 192
Void, 9