Mastering C++ Programming
Mastering C++ Programming
Programming Language
Mastering Computer Science
Series Editor: Sufyan bin Uzayr
DOI: 10.1201/9781003214762
Typeset in Minion
by KnowledgeWorks Global Ltd.
Contents
v
vi ◾ Contents
Memory Management 9
Incredible and Fast 9
Pointers 10
Compiler-Based Language 10
Syntax-Based Language 10
ALL YOU REQUIRE TO KNOW ABOUT
OBJECT-ORIENTED PROGRAMMING
IN C++ 10
What Is Object-Oriented Programming? 10
Object-Oriented Programming 11
Objects 12
Classes 12
Encapsulation 13
Abstraction 13
Polymorphism 14
Inheritance 15
C++ INSTALLATION 16
Create and Execute a C++ Console
Application Project 16
Prerequisites 16
COMMENTS 21
DATA TYPES 21
Primitive Built-In Types 21
VARIABLE TYPES 23
VARIABLE DECLARATION 24
Lvalues and Rvalues Are Two Distinct
Sorts of Qualities 26
Local Variables 26
Global Level Variables 27
Initializing Local and Global Variables 28
CONSTANTS 28
Boolean Literals 30
Literals of Characters 30
Literals in a String 31
MODIFIER 31
Qualifiers Types 32
STORAGE CLASSES 33
OPERATORS 35
Arithmetic Operators 35
Relational Operators 36
Logical Operators 36
Bitwise Operators 37
Assignment Operators 37
Misc Operators 38
OPERATORS PRECEDENCE 38
viii ◾ Contents
LOOP IN C++ 39
Control Statements for Loops 40
Infinite Loop 40
DECISION-MAKING STATEMENTS 41
CONDITIONAL OPERATOR? 41
FUNCTIONS IN C++ 42
Declarations of Functions 44
Making a Function Call 44
Arguments for Functions 44
Parameters Default Values 45
NUMBERS IN C++ 47
Numbers Defining 47
Math Operations 47
ARRAYS 48
STRINGS 49
Character String 49
String Class 51
POINTERS 52
DATE AND TIME 53
BASIC INPUT/OUTPUT 54
DATA STRUCTURES 55
Data Structures of Various Types 56
Data Structures Operations 57
OBJECT ORIENTED 57
Classes and Objects in C++ 57
Class Definitions in C++ 57
Contents ◾ ix
C++ Objects 58
Members Having Access to Data 59
Detail on Classes and Objects 60
Inheritance 61
Base and Derived Classes 61
Inheritance and Access Control 63
Types 64
Multiple Inheritance 65
OVERLOADING 67
Overloading Function 67
Overloading Operators 69
Polymorphism 72
Data Abstraction 74
Data Abstraction's Advantages 76
Encapsulation 78
Interfaces 81
HOW TO WORK WITH FILE TAKING CARE
OF IN C++? 84
Document Handling in C++ 84
File Handling in C++ 88
THE MOST EFFECTIVE METHOD
TO IMPLEMENT DATA ABSTRACTION
IN C++ 93
Abstraction in C++ 93
Kinds of Abstraction 94
Benefits of Abstraction 94
x ◾ Contents
PERFORMANCE 177
BINARY FOOTPRINT 178
NULL-TERMINATED STRING VIEW 178
FORMAT STRING SYNTAX 180
FORMAT SPECIFICATION
MINI-LANGUAGE 181
FORMATTING FUNCTIONS 187
FORMATTING ARGUMENT 188
FORMATTING ARGUMENT
VISITATION 190
CLASS TEMPLATE arg_store 191
CLASS TEMPLATE basic_args 191
FUNCTION TEMPLATE make_args 193
FORMATTING CONTEXT 193
FORMATTING BUFFER 194
FORMAT STRING 195
USER-DEFINED TYPES 195
ERROR REPORTING 196
APPRAISAL, 405
INDEX, 417
About the Editor
xxi
Chapter 1
Introduction
to C++
IN THIS CHAPTER
WHAT IS C++?
C++ is a high-level programming language developed by
Bjarne Stroustrup, and C++ operates on various platforms,
including Windows, Mac OS, and several UNIX variants.
This C++ tutorial employs a straightforward and practical
approach to conveying C++ concepts to novice to advanced
computer programmers.
C++ is a MUST for understudies and working experts to
become extraordinary Software Engineers. I’ll go through
a few of the most important advantages of learning C++:
• IBM C++
• Intel C++
• Microsoft Visual C++
• Prophet C++
• HP C++
FEATURES OF C++
There are different provisions of C++. For example:
• Object-oriented
• Simple
• Platform dependent
• Mid-level programming language
• Structured programming language
• Rich library
• Memory management
• Powerful and fast
• Pointers
• Compiler based
• Syntax-based language
OBJECT-ORIENTED PROGRAMMING
LANGUAGE
The fundamental up-degree from C to C++ is object-arranged
programming. It follows ideas of oh no like polymorphism,
legacy, epitome, reflection. This improves and supports simpler.
We should momentarily comprehend the ideas of item
arranged programming.
ELEMENTS OF C++
C++ gives an organized methodology wherein you can
break the issue into parts and plan the arrangement sepa-
rately. It gives you a rich collection of library works that
you can utilize while executing the agreement.
If you have worked with C language, moving to C++
would be an incredibly smooth progressing. The lan-
guage structure is practically comparable with minute
changes.
8 ◾ Mastering C++ Programming Language
Stage Dependent
Stage subordinate language implies can execute the lan-
guage wherein projects distinctly on that working frame-
work are created and ordered. It can’t run or manage it on
some other operational framework.
Rich Library
Designers approach heaps of in-fabricated capacities given
by C++ language. This saves time and makes advancement
quick. We should take a gander at a portion of the C++
header records and functionalities provided by it.
Memory Management
C++ upholds dynamic memory designation. You can
free the distributed memory whenever. Not just this,
C++ likewise gives dynamic memory to the executives’
procedures.
Pointers
Pointers are factors that store the location of another vari-
able. Pointer focuses on the memory area of a variable. C++
upholds pointer and gives answers for loads of issues that
request admittance to the memory area.
Compiler-Based Language
C++ is a compiler-based programming language. Without
assemblage, can be executed no C++ program. The com-
piler initially orders the C++ program, and afterward, it is
completed.
Syntax-Based Language
C++ is a language that consents unequivocally to sentence
structure. Language-keeping rules and guidelines strin-
gently are known as close punctuation-based language. C,
C++, Java, .net are a portion of the models.
• Objects
• Classes
• Encapsulation
Introduction to C++ ◾ 11
• Abstraction
• Polymorphism
• Inheritance
Object-Oriented Programming
The significant inspiration driving the innovation of the
article situated methodology is to eliminate a portion of the
blemishes experienced in the procedural method. In OOP,
information is treated as an essential component in the
program advancement and confines its stream around the
framework. It ties information near the capacity that works
on it and shields it from a coincidental adjustment from
outside powers. It permits the issue to break into various
elements called items and afterward assembles information
and capacities around these articles. The information of an
item must be gotten to by the powers related to that specific
article. Nonetheless, the elements of one thing can get to the
aspects of different themes whenever required.
It accentuation more on information as opposed to
methodology:
Objects
Objects are the most fundamental runtime elements in
OOPs. They might address user-defined information like
vectors, time and records, or anything the program needs
to deal with. Programming issue is investigated based on
objects and the idea of correspondence between them.
Articles ought to be chosen to such an extent that they
match intimately with these present reality objects. Items
occupy room in the memory and have no related location.
At the same time, execution objects interface by sending
messages to each other. For instance, on the off chance that
“Understudy” and student_rollno are two articles in a pro-
gram, the Student item might make an impression on the
student_rollno object mentioning its related Marks. Each
piece contains code to control the information.
Classes
The whole arrangement of code of an article can be made a
client characterized information type with the assistance of
class objects are factors of the kind class. When we describe
a class, we can make quite a few items having a place with
the class. Each item can be related to the information of
the type class with which they are made. In this way, a
class is only an assortment of objects of the comparable
sort. For instance, versatile, PC, and smartwatch are alto-
gether individuals from the class gadgets. Classes are client
Introduction to C++ ◾ 13
Encapsulation
Encapsulation can be characterized as wrapping up infor-
mation and data under a solitary unit. In OOP, encapsula-
tion is described as restricting together the knowledge and
the capacities that control them.
Consider a simple illustration of exemplification; there are
various areas in a school like an understudy’s part, instructors
segment, accounts segment, etc. The understudy segment han-
dles all of the understudy’s exercises and tracks all the infor-
mation identified with finance. Also, the educator holds every
one of the instructor’s connected exercises and follows every
one of the imprints and execution of understudies. Presently,
a circumstance may emerge when an understudy from the
understudy segment needs all information about imprints
and execution for reasons unknown. For this situation, he
isn’t permitted to get to the knowledge of the instructor’s com-
ponent straightforwardly. He will initially need to reach some
educator in the instructor area and afterward demand him
give everyone the information. This is the thing that exempli-
fication is. Here the knowledge of the understudy’s part and
the instructor’s segment that can control them are wrapped
under a solitary name of “educators area”.
Abstraction
Abstraction alludes to showing just the significant and
required elements of the application and concealing the
14 ◾ Mastering C++ Programming Language
1. Private
2. Protected
3. Public
Polymorphism
The word polymorphism implies having many structures.
We can characterize polymorphism as the capacity of
a capacity or information to be shown in more than one
form. An individual can have various trademarks simulta-
neously. A kid simultaneously is an understudy, a sibling,
a child so similar individual gangs diverse conduct in mul-
tiple circumstances. This is called polymorphism.
An activity can show various practices according to the
necessity in multiple occurrences. The conduct relies on
the sorts of information utilized and its needs in action.
C++ upholds administrator over-burdening and capac-
ity over-burdening:
Inheritance
Inheritance is the cycle by which objects of one class can
procure the properties, capacities, and information of
objects of another class. It follows the idea of the progres-
sive arrangement. For instance, the bird “sparrow” is a
piece of the class “flying bird”, a piece of the class “bird”.
With the assistance of this kind of division, each deter-
mined class imparts ordinary qualities and information
to the class from which it is acquired. Legacy gives the
possibility of reusability. This implies adding extra com-
ponents to a current class without adjusting or rolling out
any improvements. This is conceivable by getting another
class from the current class. The new class will obtain the
consolidated provisions of both parent and kid classes.
The genuine utilization of the legacy is that it permits the
developer to reuse a class that is nearly, however not, what
he needs, and to modify the class and make changes to not
bring any unwanted incidental effects into the remainder
of the classes. Note that each sub-class characterizes just
those interesting provisions and its rest from its parent
class. Without the utilization of any arrangement, each
class would need to expressly incorporate the entirety of
its elements which would have required some investment
and exertion.
16 ◾ Mastering C++ Programming Language
C++ INSTALLATION
Create and Execute a C++ Console Application Project
• You’ve inserted your code into a C++ console app
project. You may now create and execute it directly
from Visual Studio. Then, from the command line,
launch it as a standalone app.
Prerequisites
• Install and run Visual Studio with the Desktop devel-
opment with C++ workload on your PC. Follow the
procedures in Install C++ support in Visual Studio if
it isn’t already installed.
Getting Started
With C++
IN THIS CHAPTER
➢➢ Basic syntax
➢➢ How files are handled in C++
➢➢ File handling
In the previous chapter, we covered what C++ is, its history,
what it does, and what different types of compilers are and
learned about C++’s uses and features and how to install
C++ on a computer.
When we consider a C++ program, it tends to be char-
acterized as an assortment of articles that convey utiliz-
ing conjuring each other’s strategies. Let us currently
momentarily investigate what a class, article, strategies,
and moment factors mean.
DOI: 10.1201/9781003214762-2 17
18 ◾ Mastering C++ Programming Language
Example:
#include <iostream>
using namespace std;
// main() is where program execution
begins.
int main() {
cout << "Hello"; // prints Hello
return 0;
}
Syntax:
$ g++ example.cpp
$ ./a.out
Hello
Make sure you have g++ on your path and that you’re run-
ning it in the same directory as example .cpp
For instance
a = b;
b = b + 1;
add(a, b);
{
cout << "Hello"; // prints Hello
return 0;
}
Identifiers
A C++ identifier is used to identify a variable, function,
class, module, or any other user-defined entity. An identi-
fier in C++ starts with a letter from A to Z, a to z, or an
underscore (_), followed by zero or more letters, under-
scores, or numerals (0 to 9) and punctuation characters like
@, $, and %. C++ is a case-sensitive programming language.
Keywords
The reserved terms in C++ are shown in the table below.
These reserved terms may not be used as names for con-
stants, variables, or other types of identifiers.
COMMENTS
Explanatory statements can be included in the C++ code as
program comments. Anyone reading the source code will
benefit from these remarks. All programming languages
provide comments in some way.
Single-line and multi-line comments are supported in
C++. The C++ compiler ignores all characters available
inside each comment.
Comments in C++ begin with /* and conclude with */.
Example:
• /* This is a comment */
A comment can also start with //
• cout << "Hello World"; // prints Hello World
DATA TYPES
You must utilize numerous variables to store diverse
information while developing a program in any language.
Variables are just reserved memory regions where values
can be stored. This implies that when you make a variable,
you set aside some memory for it.
You could want to save data of different data types, such
as character, wide character, integer, floating-point, double
floating point, boolean, and so on. The operating allocating
memory determines what can be kept in reserved memory
regarding the variable’s data type.
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t
• signed
• unsigned
• short
• long
Example:
#include <iostream>
using namespace std;
int main() {
cout << "The Size of char: " <<
sizeof(char) << endl;
cout << "The Size of int: " <<
sizeof(int) << endl;
cout << "The Size of short int: " <<
sizeof(short int) << endl;
return 0;
}
Output:
The Size of char: 1
The Size of int: 4
The size of short int: 2
VARIABLE TYPES
A variable is a kind of named stockpiling that our projects
might get to. In C++, every factor has a sort that determines
24 ◾ Mastering C++ Programming Language
VARIABLE DECLARATION
A variable announcement guarantees the compiler that
there is just a single variable of the predefined type and
name, permitting the compiler to keep gathering without
knowing the entirety of the variable’s subtleties. A variable
statement possibly has significance when the program is
incorporated; the compiler requires a simple variable defi-
nition when the program is connected.
Getting Started With C++ ◾ 25
Example:
#include <iostream>
using namespace std;
// Variable declaration:
extern int x, y;
extern int z;
extern float a;
int main () {
// Variable definition:
int x, y;
int z;
float a;
// actual initialization
x = 20;
y = 10;
z = x + y;
return 0;
}
Output:
30
26 ◾ Mastering C++ Programming Language
Local Variables
Local factors are factors that are characterized inside a
capacity or square. They must be used by explanations that
are incorporated inside that capacity or code block.
Example:
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
Getting Started With C++ ◾ 27
int x, y;
int z;
// actual initialization
x = 20;
y = 10;
z = x + y;
cout << c;
return 0;
}
Example:
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int x, y;
28 ◾ Mastering C++ Programming Language
// actual initialization
x = 20;
y = 10;
z = x + y;
cout << a;
return 0;
}
CONSTANTS
Constants, often known as literals, are fixed values that the
program cannot change.
Constants are split into Integer Numerals, Floating-
Point Numerals, Characters, Strings, and Boolean Values
and can be of any fundamental data kinds.
Getting Started With C++ ◾ 29
Example:
• 212 // Legal
• 215u // Legal
• 0xFeeL // Legal
• Floating-point: A number part, a decimal point, a
partial part, and a type part make up a gliding point
exacting. Floating-point literals can be addressed in
decimal or unique structure.
You should incorporate the decimal point, the
example, or both while addressing in decimal struc-
ture and the whole number piece, the partial part, or
both while addressing in remarkable structure. e or E
presents the marked example.
• 3.14159 // Legal
• .e55 // Illegal: missing integer or fraction
• 314159E-5L // Legal
• 210f // Illegal: no decimal or exponent
• 510E // Illegal: incomplete exponent
30 ◾ Mastering C++ Programming Language
Boolean Literals
Boolean Literals are a sort of Boolean rationale.
There are two Boolean literals in C++, the two of which
are essential for the standard jargon.
Literals of Characters
Single statements are utilized to exemplify character liter-
als on the off chance that the exacting beginnings with the
letter L (capitalized just), it is a comprehensive person strict
(e.g. L‘x’) that ought to be saved in a variable of type wchar
t. Something else, it’s simply a restricted person strict (like
‘x’) that might be kept in a burn type variable.
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello\tHello\n\n";
return 0;
}
Output:
Hello Hello
Literals in a String
Double quotes are utilized to typify string literals. Plain charac-
ters, get away from groupings, and all-inclusive characters are
among the characters in a string similar to character literals.
String literals can be utilized to partition an extended
line into various lines, and whitespace can isolate them.
Example:
"Hello, ABC"
"Hello, \
ABC"
MODIFIER
C++ permits the char, int, and double data types to have
modifiers going before them. A modifier is utilized to adjust
the importance of the base sort to ensure that it all the more
definitively fits the requirements of different circumstances.
32 ◾ Mastering C++ Programming Language
• signed
• unsigned
• long
• short
Qualifiers Types
Sr. No Qualifier & Meaning
1 const
Objects of type const cannot be changed while your
application is running.
2 volatile
The modifier volatile informs the compiler that a variable’s
value can be altered in ways not explicitly indicated in the
program.
3 restrict
Initially, a pointer qualified by restricting is the only way to
access the object it references to. Only C99 introduces the
determined type qualifier.
Getting Started With C++ ◾ 33
STORAGE CLASSES
In a C++ application, a storage class specifies the scope and
lifespan of variables and functions. These specifiers come
before the type they’re changing, and they’re put before the
type they’re changing. The storage classes mentioned here
can be utilized in C++ applications.
Example:
{
int x;
auto int month;
}
Example:
{
register int m;
}
Example:
static int count = 5;
Example:
extern int c;
OPERATORS
A symbol that instructs the compiler to do certain math-
ematical or logical operations is known as an operator.
C++ has a large number of built-in operators, including
the following:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Arithmetic Operators
Relational Operators
Operator Description Example
== Condition is set to true if the values of two (C == D) is
operands are equal. not true.
!= Checks whether the values of two operands (C != D) is
are equal; if they aren’t, Condition returns true.
true.
> Checks whether the left operand’s value is (C > D) is
greater than the right operand’s value; if it is, not true.
Condition is true.
< Checks whether the left operand’s value is (C < D) is
smaller than the right operand’s value; if it is, true.
Condition is true.
>= If the left operand’s value is larger than or (C >= D) is
equal to the right operand’s value, then not true.
Condition is true.
<= The Condition is true if the left operand’s (C <= D) is
value is less than or equal to the right true.
operand’s value.
Logical Operators
Operator Description Example
&& The logical AND operator is what it’s called. (C && D)
The condition becomes true when both is false.
operands are non-zero.
|| The logical OR operator is what it’s called. (C || D) is
Condition is true if one of the two operands true.
is non-zero.
! It’s known as the Logical NOT Operator. Its !(C && D)
operand’s logical state is reversed when it is is true.
used. The Logical NOT operator returns false
if a condition is true.
Getting Started With C++ ◾ 37
Bitwise Operators
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assignment Operators
Operator Description Example
= The assignment operator is simple. Values A = C + D will
from the right side operands are assigned to assign value of
the left side operand. C + D into A
+= Using the assignment operator AND, The right A += C is
operand is added to the left operand, and the equivalent to
result is assigned to the left operand. A=A+C
-= AND (subtract AND) (assignment) (subtract A -= C is
AND) (a The right operand is subtracted equivalent to
from the left operand, and the result is A=A-C
assigned to the left operand.
*= The multiply AND assignment operator adds C *= A is
the right and left operands together and equivalent to
assigns the result to the left operand. C=C*A
/= Divide AND assignment operator: It divides A /= C is
the left operand with the right operand and equivalent to
assigns the result to the left operand. A=A/C
%= The assignment operator AND the modulus, A %= C is
uses two operands to calculate the modulus equivalent to
and assigns the result to the left operand. A=A%C
<<= Left shift AND assignment operator. A <<= 2 is same
as A = A << 2
>>= Right shift AND assignment operator. A >>= 2 is same
as A = A >> 2
&= Bitwise AND assignment operator. A &= 2 is same
as A = A & 2
^= Bitwise exclusive OR and assignment A ^= 2 is same
operator. as A = A ^ 2
|= Bitwise inclusive OR and assignment A |= 2 is same as
operator. A=A|2
38 ◾ Mastering C++ Programming Language
Misc Operators
Sr. No Operator and Description
1 sizeof
The sizeof operation returns the variable’s size. For instance,
sizeof(a), where an is an integer, returns 4.
2 Condition? X : Y
(?) is a conditional operator. If Condition is true, the value of
X is returned; otherwise, the value of Y is returned.
3 ,
A sequence of operations is done when the comma operator
is used. The value of the whole comma expression is the
value of the comma-separated list’s last expression.
4 . (dot) and -> (arrow)
Individual members of classes, structures, and unions are
referenced using member operators.
5 Cast
Casting operations change the data type of a variable.
Int(2.2000) would, for example, yield 2.
6 &
The address of a variable is returned by the pointer operator.
For example, &a; will return the variable’s real address.
7 *
A variable is pointed to by the pointer operator *. For
example, *var; refers to the variable var.
OPERATORS PRECEDENCE
The request in which terms in an expression are gathered
is dictated by operator precedence. This affects how a word
is judged. Certain administrators take need over others;
the duplication administrator, for instance, outweighs the
expansion administrator.
Getting Started With C++ ◾ 39
LOOP IN C++
You could find yourself in a situation where you need to
run a code block many times. Statements are usually exe-
cuted in the following order: the first statement in a func-
tion is executed first, followed by the second, and so on.
Programming languages offer a variety of control struc-
tures, allowing for more complicated execution paths.
Sr. No Loop Type & Description
1 while loop
While a given condition is true, it repeats a statement or a set of
assertions. Before performing the loop body, it checks the condition.
2 for loop
The code that controls the loop variable is abbreviated by executing
a sequence of instructions numerous times.
3 do...while loop
It’s similar to a ‘while’ statement, except it checks the condition at
the conclusion of the loop body.
4 nested loops
One or more loops can be used within another ‘while,’ ‘for,’ or ‘do..
while loop.
40 ◾ Mastering C++ Programming Language
Infinite Loop
A loop becomes infinite if a condition never becomes false.
The for loop is commonly used for this. Because none of the
three expressions that make up the ‘for’ loop are required,
you may create an endless loop by leaving the conditional
expression empty.
Example:
#include <iostream>
using namespace std;
int main () {
for( ; ; ) {
printf("Loop will forever run. \n");
}
return 0;
}
Getting Started With C++ ◾ 41
DECISION-MAKING STATEMENTS
The software engineer should portray at most minuscule
one Condition that the program will assess or test, just as
an articulation or explanations that will be executed if the
condition is valid. Alternatively, further proclamations
will be achieved if the condition is false.
CONDITIONAL OPERATOR?
Syntax:
Exp1? Exp2 : Exp3;
Example:
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b = 20;
return 0;
}
Output:
The value of a: 50
FUNCTIONS IN C++
A function is a group of statements that cooperate to per-
form a task. Every C++ program has at least one function,
main (), and even the simplest program can have many
functions specified.
You may break your code into different functions. It’s up
to you how you split your code into separate functions, but
logically; each function should be doing a specific purpose.
The name, return type, and parameters of a function are
all specified in a function declaration. A function defini-
tion defines the body of the function.
Getting Started With C++ ◾ 43
Function Defining
return_type function_name( parameter
list ) {
body of the function
}
Example:
int maxi(int number1, int number2) {
// local variable declaration
int result;
44 ◾ Mastering C++ Programming Language
return result;
}
Declarations of Functions
A function declaration gives the compiler the name of the
function and how to invoke it.
Syntax:
return_type function_name( parameter
list );
Example:
#include <iostream>
using namespace std;
return (result);
}
int main () {
// local variable declaration:
int x = 50;
int y = 100;
int result;
return 0;
}
Output:
Total value: 150
Total value: 60
Getting Started With C++ ◾ 47
NUMBERS IN C++
We utilize crude information types like int, short, long, buoy,
and twofold when working with Numbers. While talking
about C++ Data Types, the number information types, their
possible qualities, and number reaches were clarified.
Numbers Defining
• i = 1000;
• l = 1000000;
• f = 230.47;
Math Operations
C++ contains a large number of mathematical operations
that may be applied to a variety of integers.
Example:
#include <iostream>
#include <cmath>
using namespace std;
int main () {
// number definition:
short s = 10;
long l = 100000;
float f = 20.47;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
return 0;
}
ARRAYS
In C++, an array is a data structure that stores a fixed-size
sequential collection of objects of the same type in fixed-
size sequential order. Although an array is used to store
Getting Started With C++ ◾ 49
Syntax:
type arrayName [ arraySize ];
Sr. No Description
1 Multidimensional arrays
Multidimensional arrays are supported in C++. The two-
dimensional array is the most basic type of multidimensional
array.
2 Pointer to an array
Simply giving the array name without any index will create a
reference to the first member of the array.
3 Passing arrays to functions
By supplying the array’s name without an index, you can send
a reference to the method.
4 Return array from functions
A function in C++ can return an array.
STRINGS
There are two different sorts of string representations.
Character String
The character string was concocted in the C program-
ming language is as yet upheld in C++. This string is a
50 ◾ Mastering C++ Programming Language
Example:
#include <iostream>
using namespace std;
int main () {
char a[5] = {'H', 'e', 'l', 'l', 'o',};
cout << "Message: ";
cout << a << endl;
return 0;
}
Output:
Message: Hello
Sr. No Function
1 strcpy(s1, s2);
String s2 is copied into string s1.
2 strcat(s1, s2);
String s2 is appended to the end of string s1.
3 strlen(s1);
The length of string s1 is returned.
4 strcmp(s1, s2);
If s1 and s2 are equal, returns 0; less than 0 if s1s2; larger than
0 if s1>s2.
(Continued)
Getting Started With C++ ◾ 51
Sr. No Function
5 strchr(s1, ch);
The first occurrence of the character ch in string s1 is
returned as a pointer.
6 strstr(s1, s2);
A pointer is returned for the first occurrence of string s2 in
string s1.
String Class
The library includes a string class type that supports all of
the operations listed above and a lot more.
Example:
#include <iostream>
#include <string>
int main () {
Output:
Str2: Hello
52 ◾ Mastering C++ Programming Language
POINTERS
C++ pointers are easy to understand and use, and while
some C++ tasks are simpler with them, others, such as
dynamic memory allocation, cannot be done without
them.
A pointer is a variable whose value is the location of
another variable. Before using a pointer, just like any other
variable or consistent, it should be pronounced.
Syntax:
type *var-name;
Sr. No Description
1 Null Pointers
Null pointer, a constant with a zero value defined in various
standard libraries, is supported in C++.
2 Pointer Arithmetic
On pointers, the arithmetic operators ++, --, +, and - can be
utilized.
3 Pointers vs. Arrays
Pointers and arrays have a very close relationship.
4 Array of Pointers
Arrays can be used to hold many pointers.
5 Pointer to Pointer
You can have a pointer on a pointer in C++, and so on.
(Continued)
Getting Started With C++ ◾ 53
Sr. No Description
6 Passing Pointers to Functions
Passing an argument by reference or by address allows the
called function to modify the supplied argument in the
calling code.
7 Return Pointer from Functions
A function in C++ can return a pointer to a local variable, a
static variable, or dynamically allocated memory.
Sr. No Function
1 time_t time(time_t *time);
This returns the system’s current calendar time as a number
of seconds since January 1, 1970. If the system does not
have any time, a value of.1 is returned.
2 char *ctime(const time_t *time);
This function produces a string of the form day month year
hours:minutes:seconds year\n\0.
(Continued)
54 ◾ Mastering C++ Programming Language
Sr. No Function
3 struct tm *localtime(const time_t *time);
This gives you a pointer to the tm structure, which is used
to indicate local time.
4 clock_t clock(void);
This gives you a rough estimate of how long the calling
application has been running. If the time is unavailable, a
value of.1 is returned.
5 char * asctime ( const struct tm * time );
This returns a reference to a string containing the data
contained in the structure pointed to by time, which has
been transformed to the form: date (day, month) seconds:
minutes: hours: minutes: hours: minutes: minutes:
minutes: minutes: minutes year\n\0.
6 struct tm *gmtime(const time_t *time);
This returns a tm structure with a reference to the time.
Coordinated Universal Time (UTC), which is basically
Greenwich Mean Time, is used to indicate the time (GMT).
7 time_t mktime(struct tm *time);
The calendar-time equivalent of the time in the structure
referenced to by time is returned.
8 double difftime ( time_t time2, time_t time1 );
The difference in seconds between time1 and time2 is
calculated using this function.
9 size_t strftime();
This function allows you to format the date and time in a
specified way.
BASIC INPUT/OUTPUT
Input/Output occurs in streams, which are byte-by-byte
successions. The progression of bytes from a gadget like a
console, a circle drive, or an organization association with
principle memory is known as info, while the progres-
sion of bytes from fundamental memory to a gadget, for
example, a presentation screen, a printer, a plate drive, or
an organization association is known as yield.
Getting Started With C++ ◾ 55
DATA STRUCTURES
Data structures are a huge and unavoidable element of
any programming project. Cells, the tiniest unit of life,
are just as reliant on us humans for a variety of biological
processes. The basic unit of programming known as “data”
underpins the whole C++ program. The implementation of
data structures allows us to conduct data operations such
as data representation, storage, organization, and many
others in a meaningful way.
An information type is just an assortment of comparable
information with a similar name. Comparable information
types have comparable properties and act comparatively,
like taking up a similar measure of PC memory and serv-
ing a similar capacity.
There are two significant kinds of information:
OBJECT ORIENTED
Classes and Objects in C++
The fundamental goal of C++ programming is to intro-
duce object orientation to the C programming language,
and classes, also known as user-defined types, are the key
element of C++ that allows object-oriented programming.
A class specifies an object’s form by combining data
representation and methods for changing that data into a
single package. Members of a class are the data and meth-
ods that make up the class.
define what the class name implies, that is, what a class
object will be made up of and what actions can be done on it.
The keyword class is used to start a class definition, fol-
lowed by the class name, and lastly the class body, which
is enclosed by a pair of curly brackets. A semicolon or a
series of declarations must come after a class definition. For
example, we used the term class to define the Box data type:
Example:
class B {
public:
double length;
double breadth;
double height;
};
C++ Objects
A class serves as the blueprint for things, thus an object
is essentially produced from one. Objects of a class are
declared in the same way as variables of fundamental
types are declared. The following statements declare two
Car objects:
Car Car1;
Car Car2;
Getting Started With C++ ◾ 59
#include <iostream>
using namespace std;
class box {
public:
double length;
double breadth;
double height;
};
int main() {
box box1;
box box2;
double volume = 0.3;
// specification
box1.height = 3.0;
box1.length = 4.0;
box1.breadth = 7.0;
// specification
box2.height = 20.0;
box2.length = 21.0;
box2.breadth = 14.0;
// volume
volume = box1.height * box1.length *
box1.breadth;
cout << "The Volume of box1: " << volume
<<endl;
60 ◾ Mastering C++ Programming Language
// volume of box 2
volume = box2.height * box2.length *
box2.breadth;
cout << "The Volume of box2: " << volume
<<endl;
return 0;
}
Output:
The Volume of box1: 84
The Volume of box2: 5880
Sr. No Description
4 Copy Constructor:
The copy function is a function that produces an object by
initialising it using a previously generated object of the same
class.
5 Friend Functions:
A friend function has full access to a class’s private and
protected members.
6 Inline Functions:
In the case of an inline function, the compiler tries to extend
the code in the body of the function rather than calling it.
7 this Pointer:
Every object has a unique pointer that refers to the actual object.
8 Pointer:
A class pointer is created in the same manner as a structure
pointer is created. In reality, a class is nothing more than a
structure containing functions.
9 Static Members:
A class’s data and function members can both be declared static.
Inheritance
The idea of inheritance is one of the most essential in object-
oriented programming. Inheritance enables us to define a
class in terms of another class, which simplifies application
development and maintenance. This also allows for the reuse
of code functionality and a quick implementation time.
Instead of developing entirely new data members and
member methods when establishing a class, the program-
mer can specify that the new class should inherit the mem-
bers of an existing class. The current class is known as the
base class, while the new class is known as the derived
class. Inheritance is a connection that is implemented.
Example:
#include <iostream>
// Class-Base
class shape {
public:
void setWidth(int w) {
wd = w;
}
void setHeight(int h) {
hg = h;
}
protected:
int wd;
int hg;
};
// Derived-class
class rect: public shape {
public:
Getting Started With C++ ◾ 63
int getArea() {
return (wd * hg);
}
};
int main(void) {
rect r;
r.setWidth(5);
r.setHeight(7);
// Print
cout << "The Total area: " <<
r.getArea() << endl;
return 0;
}
Output:
The Total area: 35
Types
When creating a class from a base class, the base class can
be inherited in one of three ways: public, protected, or pri-
vate inheritance. As previously stated, the access-specifier
specifies the type of inheritance.
Protected and private inheritance is rarely utilized,
while public inheritance is. The following principles apply
when utilizing various types of inheritance:
Multiple Inheritance
A C++ class can inherit members from multiple classes,
and the expanded syntax is as follows:
Example:
#include <iostream>
// Base class
class shape
{
public:
void setWidth(int w) {
wd = w;
}
void setHeight(int h)
{
hg = h;
}
66 ◾ Mastering C++ Programming Language
protected:
int wd;
int hg;
};
// Base class
class paintcost {
public:
int getCost(int ar) {
return ar * 30;
}
};
// Derived class
class Rect: public shape, public
paintcost {
public:
int getArea() {
return (wd * hg);
}
};
int main(void) {
Rect r;
int ar;
r.setWidth(7);
r.setHeight(8);
ar = r.getArea();
return 0;
}
Output:
The Total area: 56
The Total paint cost:1680
OVERLOADING
Function overloading and operator overloading are terms
used in C++ to describe the ability to specify several defini-
tions for a function name or an operator in the same scope.
An overloaded declaration is one that has the same name
as a previously declared declaration in the same scope, but
both declarations have distinct parameters and clearly dif-
ferent definitions.
The compiler determines which definition to apply when
you call an overloaded function or operator by comparing
the argument types you used to invoke the function or
operator to the parameter types supplied in the definitions.
Overloading Function
In C++, function overloading means that the same func-
tion name can have several definitions in the same scope.
The kinds and/or the number of arguments in the argu-
ment list must be different in each function declaration.
Overloading function declarations that differ only in
return type is not possible.
68 ◾ Mastering C++ Programming Language
Example:
#include <iostream>
using namespace std;
class printd {
public:
void print(int j) {
cout << "Printing int: " << j
<< endl;
}
void print(double h) {
cout << "Printing float: " << h
<< endl;
}
void print(char* b) {
cout << "Printing character: "
<< b << endl;
}
};
int main(void) {
printd pd;
// Call print
pd.print(4);
// Call print
pd.print(400.223);
// Call print
pd.print("Hello ");
return 0;
}
Getting Started With C++ ◾ 69
Output:
Printing int: 4
Printing float: 400.223
Printing character: Hello
Overloading Operators
In C++, you may redefine or overload most of the built-
in operators. As a result, a programmer may also utilize
operators with user-defined types.
Overloaded operators are functions with unique names,
consisting of the keyword "operator" followed by the symbol
for the operator to be defined. An overloaded operator, like
any other function, has a return type and an argument list.
Syntax:
box operator+(const box&);
Syntax:
box operator+(const box&, const box&);
Example:
#include <iostream>
using namespace std;
class box {
public:
double getVolume(void) {
return leng * bread * heig;
}
void setLength( double len ) {
leng = len;
}
void setBreadth( double bre ) {
bread = bre;
}
void setHeight( double hei ) {
heig = hei;
}
return boxx;
}
private:
double leng;
double bread;
double heig;
};
// Main function
int main() {
box box1;
box box2;
box box3;
double volume = 0.0;
// specification
box1.setLength(8.0);
box1.setBreadth(4.0);
box1.setHeight(6.0);
// specification
box2.setLength(11.0);
box2.setBreadth(14.0);
box2.setHeight(12.0);
// volume
volume = box1.getVolume();
cout << "Volume of box1 : " <<
volume <<endl;
// volume
volume = box2.getVolume();
cout << "Volume of box2 : " <<
volume <<endl;
72 ◾ Mastering C++ Programming Language
// volume
volume = box3.getVolume();
cout << "Volume of box3 : " <<
volume <<endl;
return 0;
}
Output:
Volume of box1: 192
Volume of box2: 1848
Volume of box3: 6156
Polymorphism
Polymorphism refers to the fact that something exists
in several forms. Polymorphism usually happens when
there is a hierarchy of classes that are connected through
inheritance.
Polymorphism in C++ refers to the fact that depending
on the kind of object that calls a member function, a differ-
ent function is performed.
Consider the following scenario, in which a base class is
derived from two additional classes:
Example:
#include <iostream>
using namespace std;
Getting Started With C++ ◾ 73
class shape {
protected:
int wd, hg;
public:
Shape( int w = 0, int h = 0){
width = w;
height = h;
}
int ar() {
cout << "The Parent class area
:" <<endl;
return 0;
}
};
class rectangle: public shape {
public:
rectangle( int w = 0, int h =
0):Shape(w, h) { }
int ar () {
cout << "The Rectangle class
area :" <<endl;
return (wd * hg);
}
};
int ar () {
cout << "The Triangle class
area :" <<endl;
74 ◾ Mastering C++ Programming Language
// Main function
int main() {
shape *sh;
rectangle rc(10,7);
triangle tr(10,5);
return 0;
}
Output:
The Parent class area :
The Parent class area :
Data Abstraction
Data abstraction refers to simply exposing important infor-
mation to the outer world while hiding background details,
i.e. to represent the needed information in a programme
without displaying the intricacies.
Getting Started With C++ ◾ 75
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello " <<endl;
return 0;
}
76 ◾ Mastering C++ Programming Language
You don’t need to know how cout displays text on the user’s
screen in this case. You just need to understand the public
interface; the underlying implementation of ‘cout’ can be
changed at any time.
Example:
#include <iostream>
using namespace std;
class Add {
public:
Getting Started With C++ ◾ 77
// constructor
Add(int a = 0) {
t = a;
}
int getTotal() {
return t;
};
private:
// hidden data
int t;
};
int main() {
Add ad;
ad.addNumb(10);
ad.addNumb(20);
ad.addNumb(30);
Output:
Total: 60
78 ◾ Mastering C++ Programming Language
Encapsulation
The following two essential components are present in all
C++ programs:
Functions are the parts of a program that perform
actions, and they are termed program statements.
Program data is the program’s information that is influ-
enced by the program’s functions.
Encapsulation is a notion in Object Oriented Programming
that ties together data and the functions that change it, keep-
ing both protected from outside intervention and misuse.
The essential OOP idea of data hiding was born from data
encapsulation.
Data abstraction is a technique for exposing only the
interfaces and hiding the implementation details from the
user, whereas data encapsulation is a strategy for packag-
ing data and the functions that utilize it.
Encapsulation and data hiding are supported in C++ via
the use of classes, which are user-defined types. We’ve pre-
viously seen that a class can have members who are secret,
protected, or public. All items declared in a class are pri-
vate by default.
Example:
class box {
public:
double getVol(void) {
return len * bread * heig;
}
private:
double len;
Getting Started With C++ ◾ 79
double bread;
double heig;
};
The length, width, and height variables are all private. This
implies that they can only be accessible by other Box class
members and not by any other component of your applica-
tion. This is one method of encapsulation.
You must define sections of a class after the public keyword
to make them public (i.e., available to other parts of your pro-
gram). All other functions in your application can access any
variables or functions declared after the public specifier.
By making one class a buddy of another, the implemen-
tation details are exposed and encapsulation is lost. The
ideal situation is to keep as many of each class’s informa-
tion hidden from other classes as possible.
Example:
#include <iostream>
using namespace std;
class Add {
public:
// constructor
Add(int a = 0) {
total = a;
}
// interface
void addNum(int numb) {
total += numb;
}
80 ◾ Mastering C++ Programming Language
// interface
int getTotal() {
return total;
};
private:
// hidden data
int total;
};
int main() {
Add ad;
ad.addNum(20);
ad.addNum(30);
ad.addNum(10);
Output:
Total: 60
Interfaces
An interface specifies a C++ class’s behavior or capabilities
without committing to a specific implementation of that
class.
Abstract classes are used to implement C++ interfaces.
These abstract classes should not be confused with data
abstraction, which is a notion that separates implementa-
tion details from related data.
A class becomes abstract when at least one of its func-
tions is declared as a pure virtual function. The expres-
sion “= 0” in the declaration of a pure virtual function is
as follows:
Example:
class box {
public:
// virtual function
virtual double getVol() = 0;
private:
double len; // Box Length
double bread; // Box Breadth
double heig; // Box Height
};
Example:
#include <iostream>
using namespace std;
// Base class
class shape {
public:
// pure virtual function
virtual int getAr() = 0;
void setWidth(int wd) {
wid = wd;
}
protected:
int wid;
int hei;
};
// Derived class
class rectangle: public shape {
public:
int getAr() {
return (wid * hei);
Getting Started With C++ ◾ 83
}
};
int main(void) {
rectangle rect;
triangle tri;
rect.setWidth(6);
rect.setHeight(4);
// Print
cout << "The Total Rectangle area: "
<< rect.getAr() << endl;
tri.setWidth(5);
tri.setHeight(7);
// Print
cout << "The Total Triangle area: "
<< tri.getAr() << endl;
return 0;
}
Output:
The Total Rectangle area: 24
The Total Triangle area: 17
84 ◾ Mastering C++ Programming Language
• Opening a File
• Close a File
Source Code:
/* File Handling with C++ using
ifstream & ofstream */
/* To write the Content */
/* Read the content*/
#include <iostream>
#include <fstream>
86 ◾ Mastering C++ Programming Language
// Driver Code
int main()
{
string line;
// Press -1 to exit
if (line == "-1")
break;
return 0;
}
All the over three classes are gotten from fstreambase and
the comparing iostream class and they are planned explic-
itly to oversee circle documents.
C++ gives us the accompanying tasks in File Handling:
Syntax:
void open(const char* file_
name,ios::openmode mode);
Modes Description
in The file is opened for reading.
out Opens the file that will be written to.
binary The file is opened in binary mode.
app Opens the file and, at the end, appends all of the outputs.
ate The file is opened, and the control is moved to the end
of the file.
trunc The data in the existing file is deleted.
nocreate If the file already exists, it will be opened.
noreplace If the file does not already exist, it is opened.
Syntax:
fstream new_file;
new_file.open("newfile.txt", ios::out);
Getting Started With C++ ◾ 89
Syntax:
ofstream new_file;
new_file.open("new_file.txt", ios::out
| ios::app );
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing
file
}
return 0;
}
Output:
New file created
• Writing to a File
Source Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
Getting Started With C++ ◾ 91
{
fstream new_file;
new_file.open("new_file_write.
txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning"; //Writing to
file
new_file.close();
}
return 0;
}
Output:
New file created
new_file.open("new_file_write.
txt",ios::in);
if(!new_file)
cout<<"No such file"; } else { char ch;
while (!new_file.eof()) { new_file >>ch;
cout << ch;
}
new_file.close();
return 0;
}
Syntax:
File Pointer.close()
Source Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.
txt",ios::out);
new_file.close();
return 0;
}
Output:
The file gets closed.
Getting Started With C++ ◾ 93
Abstraction in C++
Think about a model: An individual uses a cell phone
except if he is from an IT or ECE foundation, he knows
nothing other than what catches to press. This is a legiti-
mate illustration of Data Abstraction.
Kinds of Abstraction
There are two sorts of Abstraction:
1. Data Abstraction
2. Control Abstraction
Benefits of Abstraction
Source Code:
#include<iostream>
using namespace std;
class test
{
Getting Started With C++ ◾ 95
private:
int x;
public:
test(int a)
{
x =a;
}
int get()
{
return x;
}
};
int main()
{
test a(5);
cout<<"Number is: "<<a.get();
return 0;
}
Output:
Number is: 5
Source Code:
#include<iostream>
using namespace std;
class test1
{
private:
int a;
public:
test(int a1)
{
a = a1;
}
test1(const test1 &c2)
{
x = c2.a;
}
int getB()
{
return a;
}
};
Getting Started With C++ ◾ 97
int main()
{
test c1(6); // Normal constructor is
called here
test c2 = c1; // Copy constructor is
called here
cout << "c1.a = " << c1.getB();
cout << "nc2.x = " << c2.getB();
return 0;
}
Output:
c1.a = 6
c2.a = 6
DATA HIDING
Data hiding is a platform developed for hiding internal
object information, such as data members, in object-ori-
ented programming. Data hiding ensures confined infor-
mation admittance to class individuals and keeps up with
object uprightness. In this blog, we will see how informa-
tion concealing functions in C++.
• Encapsulation
• Abstraction
• Data Hiding
• Program explanations
• Program information
Encapsulation
Encapsulation ties the information and capacities together,
which keeps the two safes from the outside impedance.
Information epitome prompted statement stowing away.
Source Code:
#include<iostream>
using namespace std;
class Encap
{
private:
// data hidden from outside
world
int number;
public:
// function to set value of
// variable a
void set(int x)
{
number =x;
}
// function to return value of
// variable a
int get()
{
return number;
}
};
// main function
Getting Started With C++ ◾ 99
int main()
{
Encap object;
object.set(3);
cout<<object.get();
return 0;
}
Output:
3
Abstraction
Data Abstraction is an instrument of concealing the execu-
tion from the client and uncovering the interface.
Source Code:
#include <iostream>
using namespace std;
class Abstraction
{
private:
int number1, number2;
public:
void set(int x, int y)
{
number1 = x;
number2 = y;
}
void display()
{
cout<<"number1 = " <<number1
<< endl;
100 ◾ Mastering C++ Programming Language
Output:
number1 = 20
number2 = 50
Data Hiding
Data Hiding is a course of joining information and capaci-
ties into a solitary unit. The philosophy behind statement
stowing away is to cover information inside a class, to
keep its immediate access from outside the class. It assists
software engineers in making classes with unique infor-
mational indexes and capacities, keeping away from extra
infiltration from other program classes.
Talking about Data Hiding and information embodi-
ment, information concealing shrouds class information
parts, though information epitome shrouds class informa-
tion parts and private strategies.
Presently you likewise need to know the entrance speci-
fier for understanding information stowing away.
Private, public, and protected are three kinds of secu-
rity/access specifiers accessible inside a class. Generally, the
Getting Started With C++ ◾ 101
Source Code:
#include<iostream>
using namespace std;
class Base1{
void read();
void print();
};
}
int main(){
Base1 object;
object.read();
object.print();
return 0;
}
Output:
Enter value 5
Value is 5
• Constructor
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Destructor
• Virtual Destructor
Getting Started With C++ ◾ 103
Default Constructor
A default constructor is a sort of constructor that doesn’t
take any contention and has no parameters.
104 ◾ Mastering C++ Programming Language
Source Code:
#include <iostream>
using namespace std;
class test {
public:
int y, z;
test()
{
y = 8;
z = 11;
}
};
int main()
{
test a;
cout <<"the sum is: "<< a.y+a.z;
return 1;
}
Output:
19
Parameterized Constructor
The passing of parameters to the constructor is conceiv-
able. This is done to introduce the worth of utilizing these
passed boundaries. This kind of constructor is known as a
Parameterized constructor.
The constructor is characterized as follows:
test(int x2)
{
x = x2;
}
Getting Started With C++ ◾ 105
test c(20);
Source Code:
include <iostream>
using namespace std;
class test {
public:
int a;
test(int a1)
{
a = a1;
}
int getB()
{
return a;
}
};
int main()
{
test c(20);
cout << "b.a = " << b.getB();
return 0;
}
Output:
b.a = 20
106 ◾ Mastering C++ Programming Language
Copy Constructor
A Copy Constructor is a Constructor which introduces an
object of a class utilizing one more object of a similar class.
Source Code:
#include<iostream>
using namespace std;
class test1
{
private:
int a;
public:
test(int a1)
{
a = a1;
}
test(const test &c2)
{
x = c2.x;
}
int getB()
{
return a;
}
};
int main()
{
test c1(5); // Normal constructor is
called here
test c2 = c1; // Copy constructor is
called here
cout << "c1.a = " << c1.getB();
cout << "nc2.a = " << tc2.getB();
Getting Started With C++ ◾ 107
return 0;
}
Output:
c1.x = 5
c2.x = 5
Destructor
Destructors are one more sort of part work that is
answerable for obliterating or erasing the item. It opens
up space involved by the item after it is at this point
not required. A Destructor is called naturally when the
article is out of extension and as of now not required. A
Destructor has the name same as the class name, how-
ever, the lone distinction is that the name is gone before
by a tile ~.
Syntax:
~test1
• Function closes
• Program close
108 ◾ Mastering C++ Programming Language
Source Code:
#include <iostream>
using namespace std;
class test1 {
public:
int a, b;
test1()
{
a = 5;
b = 10;
}
~test1(){ }
};
int main()
{
test x;
cout <<"the sum is: "<< x.a+x.b;
return 1;
}
Output:
15
Virtual Destructor
The lone variety to the destructor is making the destructor
virtual. This is done when we have an inheritance. During
inheritance, the typical destructor acts vaguely. To fix
Getting Started With C++ ◾ 109
class base1 {
public:
base1()
{ cout<<"Base Constructor n"; }
virtual ~base1()
{ cout<<"Base Destructor"; }
};
Example:
#include <iostream>
int main() {
char str[] = "Hi everyone";
Example:
#include <iostream>
using namespace std;
int main() {
char n[30];
cout << "Enter your name: ";
cin >> n;
cout << "Your name: " << n << endl;
}
When you compile and run the code above, it will request
you for a name. To see the following result, you enter a
value and then press enter.
Example:
#include <iostream>
using namespace std;
int main() {
char str[] = "Un-able to read";
cerr << "Error: " << str << endl;
}
When the given code is built and run, the following result
is obtained:
Example:
#include <iostream>
using namespace std;
int main() {
char str[] = "Un-able to read";
clog << "Error: " << str << endl;
}
• Title
• Author
• Subject
• Book-id
Structure Defining
The struct statement is used to define a structure. The
struct command creates a new data type for your appli-
cation with many members. The struct statement has the
following format:
Syntax:
struct [struc tag] {
member definition;
....
member definition;
};
Example:
struct books {
char title[70];
char author[60];
char subject[90];
int book_id;
} book;
Example:
#include <iostream>
#include <cstring>
struct books {
char title[70];
char author[60];
char subject[90];
int book_id;
};
int main() {
struct books book1;
//
Declare Book1 of type Book
116 ◾ Mastering C++ Programming Language
// Print
cout << "Booktitle : " << book1.
title <<endl;
cout << "Bookauthor : " << book1.
author <<endl;
cout << "Booksubject : " << book1.
subject <<endl;
cout << "Bookid : " << book1.book_id
<<endl;
// Print
cout << "Booktitle : " << book2.
title <<endl;
cout << "Bookauthor : " << book2.
author <<endl;
cout << "Booksubject : " << book2.
subject <<endl;
cout << "Bookid : " << book2.book_id
<<endl;
return 0;
}
Getting Started With C++ ◾ 117
Output:
Booktitle : C++ Programming
Bookauthor : Chandi
Booksubject : C++
Bookid : 64407
Booktitle : Billi
Bookauthor : hakita
Booksubject : Tele
Bookid : 64700
#include <iostream>
#include <cstring>
struct books {
char title[70];
char author[60];
char subject[90];
int book_id;
};
int main() {
struct books book1;
// Declare
Book1 of type Book
struct books book2;
// Declare
Book2 of type Book
118 ◾ Mastering C++ Programming Language
// specification of book 1
strcpy( book1.title, " C++ Programming");
strcpy( book1.author, "Chandi ");
strcpy( book1.subject, "C++ ");
book1.book_id = 64407;
// book 2 specification
strcpy( book2.title, " Billi");
strcpy( book2.author, "hakita");
strcpy( book2.subject, "Tele");
book2.book_id = 64700;
// Print book1info
printbook( book1 );
return 0;
}
void printbook( struct books book ) {
cout << "Booktitle : " << book.title
<<endl;
cout << "Bookauthor : " << book.author
<<endl;
cout << "Booksubject : " << book.subject
<<endl;
cout << "Bookid : " << book.book_id
<<endl;
}
Output:
Booktitle : C++ Programming
Bookauthor : Chandi
Getting Started With C++ ◾ 119
Booksubject : C++
Bookid : 64407
Booktitle : Billi
Bookauthor : hakita
Booksubject : Tele
Bookid : 64700
Working With
Numbers and
Spaces
IN THIS CHAPTER
Function Description
stoi A string is converted to an integer using this method.
stol
stoll
atoi A byte string is converted to an integer using this method.
atol
atoll
stod Floating-point values are transformed from bytes.
stof
stold
stoul A byte string is converted to an unsigned integer using
stoull this method.
Example:
//C++ code to demonstrate working of
lexical_cast()
#include<iostream>
#include <boost/lexical_cast.hpp>
#include <string> // for string
using namespace std;
int main()
{
string str = "4";
string str1 = "4.5";
124 ◾ Mastering C++ Programming Language
return 0;
}
Output:
The float value after casting: 4.5
The int value after casting: 4
Example:
// C++ code to demonstrate string
stream method
// to convert number to string.
#include<iostream>
Working With Numbers and Spaces ◾ 125
return 0;
}
Output:
Newly formed string from number: 2020
Example:
// C++ code to demonstrate "to_string()"
method
// to convert number to string.
#include<iostream>
#include<string> // for string and
to_string()
using namespace std;
int main()
{
// Declaring integer
int i_val = 10;
// Declaring float
float f_val = 20.50;
return 0;
}
Working With Numbers and Spaces ◾ 127
Output:
The integer in string: 10
The float in string: 20.500000
Example:
// C++ code to demonstrate "lexical_
cast()" method
// to convert number to string.
#include <boost/lexical_cast.hpp> //
for lexical_cast()
#include <string> // for string
using namespace std;
int main()
{
// Declaring float
float f_val = 8.5;
// Declaring int
int i_val = 14;
// lexical_cast() converts a float
into string
string strf = boost::lexical_cast
<string>(f_val);
// lexical_cast() converts a int into
string
128 ◾ Mastering C++ Programming Language
Output:
The float value in string: 8.5
The int value in string: 14
Maximum Minimum/
Maximum Subscript Elements per Maximum Maximum Size
Range Dimension Dimensions (in bytes)
[*][–2,147,483,648, [*]+2,147,483,647 1/9 [*]+2,147,483,647
+2,147,483,647]
• Integer
• Character
• Boolean
• Floating Point
• Valueless or Void
• Wide Character
1. Function
2. Array
3. Pointer
4. Reference
• Class
• Structure
• Union
• Enumeration
• Typedef defined DataType
Integers
In programming, integers are classified into three cat-
egories: short int, int, and long int. A short int can be
any integer between –32,768 and 32,767, but a regular int,
sometimes known as just int, has a much more extensive
range, ranging from 2,147,483,648 to 2,147,483,647.
It’s crucial to remember that in C++, there’s no one stan-
dard for numeric data types. Thus the names and range
134 ◾ Mastering C++ Programming Language
Example
out << 'short int Min/Max : ' << SHRT_
MIN << ' / ' << SHRT_MAX << endl;
cout << 'int Min/Max : ' << INT_MIN <<
' / ' << INT_MAX << endl;
cout << 'long Min/Max : ' << LONG_MIN
<< ' / ' << LONG_MAX << endl;
Decimal
The decimal data type is a very exact numeric data type
distinguished by its accuracy and scale.
Floating Points
The second category of numeric data types in C++ is floats.
As the name indicates, floating points can have a decimal,
providing them a higher level of precision than integers.
In C++, floating-point numbers are divided into three
categories: float, double, and long double. Floats are the
smallest, followed by images, which are twice the size of
doubles, and long doubles, which are twice the size of long
doubles. The code below will provide an output that shows
the float data types’ lowest and maximum values.
Example
cout << '\tFloat \t\t' << 'Double \t\t'
<< 'Long Double' << endl;
cout << 'Min : ' << FLT_MIN << '\t' <<
DBL_MIN << '\t' << LDBL_MIN << endl;
Working With Numbers and Spaces ◾ 135
Example:
auto b = true; // boolean
auto s = "sam"; // const char[7]
auto i = 18; // int
auto d = 18.0; // double
// with prefixes
auto w = L"Hello"; // const wchar_t[5]
auto h = 0xBAD; // int (in
hexadecimal representation)
// with suffixes
auto a = 18u; // unsigned int
auto l = 18l; // signed long
auto f = 18.0f; // float
COOKED
The literal 0xBAD is “0”, “x”, “B”, “A”, “D” in raw form
and a compiler-interpreted type of characters; the literal
0xBAD is the integer 2898 in cooked form.
Cooked Literals
For a cooked literal, the literal operator has the following
form:
Example
OutputType operator "" _suffix(InputType);
Example:
OutputType operator "" _suffix(unsigned
long long);
Working With Numbers and Spaces ◾ 137
Example:
OutputType operator "" _suffix(long
double);
Example
OutputType operator "" _suffix(char);
OutputType operator "" _suffix
(wchar_t);
OutputType operator "" _suffix
(char16_t);
OutputType operator "" _suffix
(char32_t);
LITERALS OF RAW
Only integral and floating-point types support raw literals.
The literal operator for a cooked literal is as follows (note
that the operator does not take a second parameter to spec-
ify the size of the string; the string is null-terminated):
Example
class Emp
{
std::string name;
Working With Numbers and Spaces ◾ 139
public:
Emp(std::string const & name)
:name(name){}
std::string getName() const { return
name; }
};
int main()
{
140 ◾ Mastering C++ Programming Language
auto e = "mari"_dev;
auto d = "Tia"_qa;
std::cout << d.getName() << std::endl;
std::cout << q.getName() << std::endl;
return 0;
}
Example:
#include <complex>
int main()
{
using namespace
std::literals::complex_literals;
std::complex<double> c = 1.0 + i;
}
Example
#include <chrono>
int main()
{
Working With Numbers and Spaces ◾ 141
using namespace
std::literals::chrono_literals;
auto timer = 2h + 20min + 20s;
}
Example
int main()
{
using namespace
std::string_literals;
std::string d1 = "text\0"; // d1
= "text"
std::string d2 = "text\0"s; // d2
= "text\0"
}
STRING HELPER
The String Helper file includes methods to help with string
manipulation.
Syntax:
$this->load->helper('string');
142 ◾ Mastering C++ Programming Language
Syntax:
random_string([$type = 'alnum'[, $len
= 8]])
Parameters:
• $type (string): Randomization type
• $len (int): Output string length
Returns: A random string
Return type: string
The type and length you give are used to generate a ran-
dom string. It may be used to create passwords or generate
random hashes.
The first argument determines the string’s type, while
the second specifies its length. There are multiple options
available:
Example:
echo random_string('alnum', 26);
Parameters:
• $str (string): String to be entered
• $separator (string): Append a duplicate number with
a separator
• $first (int): Number to begin with
Returns: a string that has been increased in length
Return type: string
Example:
echo increment_string('file', '_'); //
echo increment_string('file', '-', 3);
echo increment_string('file_5');
• alternator($args)
144 ◾ Mastering C++ Programming Language
Parameters:
• $args (mixed): The number of parameters is vary.
Returns: Alternated string
Return type: mixed
Example:
for ($i = 0; $i < 10; $i++)
{
echo alternator('string one',
'string two');
}
Example:
for ($i = 0; $i < 10; $i++)
{
echo alternator('one', 'two',
'three', 'four', 'five');
}
Parameters:
• $data (string): Input
• $num (int): The number of times you should repeat it
Working With Numbers and Spaces ◾ 145
Example:
$string = "\n";
echo repeater($string, 30);
• reduce_double_slashes($str)
Parameters: $str (string)—String to be entered
Returns: Slashes that have been normalized in a string
Return type: string
Example:
$string = "http://example.com//index.
php";
echo reduce_double_slashes($string);
• strip_slashes($data)
Example:
$str = array(
'question' => 'your name O\
illy?',
'answer' => ' my name is
O\'nnor.'
);
$str = strip_slashes($str);
• trim_slashes($str)
Example:
$string = "/this/that/theother/";
echo trim_slashes($string);
Parameters:
• $str (string): Text to look for
• $character (string): Reduced character
• $trim (bool): Whether the supplied character should
additionally be trimmed
Returns: Reduced string length
Type of return: string
Working With Numbers and Spaces ◾ 147
Example:
$string = "Fill, hill, Toe, Jim";
$string = reduce_multiples($string,",")
• quotes_to_entities($str)
Example:
$string = "Toe's \"food\"";
$string = quotes_to_entities($string);
• strip_quotes($str)
Example:
$string = "Toe's \"food\"";
$string = strip_quotes($string);
148 ◾ Mastering C++ Programming Language
TEXT HELPER
This file includes routines that make dealing with text
easier.
Syntax:
$this->load->helper('text');
Available Functions
The following functionalities are accessible:
• word_limiter($str[, $limit = 100[, $end_char =
‘Ѫ’]])
Parameters:
• $str (string): String to be entered
• $limit (int): Limit
• $end_char (string): Character’s end
Returns: String with a word limit
Type of return: string
Example:
$string = " String consisting of eleven
words.";
$string = word_limiter($string, 5);
Parameters:
• $str (string): String to be entered
• $n (int): the total number of characters
• $end_char (string): Character’s end
Returns: String with a character limit
Type of return: string
Example:
$string = "String consisting of eleven
words.";
$string = character_limiter($string, 20);
Example:
$string = ascii_to_entities($string);
• convert_accented_characters($str)
Example:
$string =
convert_accented_characters($string);
Parameters:
• $str (string): String to be entered
• $censored (array): List of terms that should be avoided
• $replacement (string): What should be used to replace
bad words
Returns: Censored string
Return type: string
Example:
$disallowed = array('darn', 'shucks',
'golly', 'phooey');
$string = word_censor($string,
$disallowed, ’Beep!’);
• highlight_code($str)
Example:
$string = highlight_code($string);
152 ◾ Mastering C++ Programming Language
TYPOGRAPHY ASSIST
The Typography Helper file includes routines that aid in
the semantically appropriate formatting of text.
This helper is currently being loaded.
• Available Functions
• Loading this Helper
Example:
$this->load->helper('typography');
Available Functions
There are the following functions available:
• auto_typography($str[, $reduce_linebreaks = FALSE])
Parameters:
• $str (string): Input string
• $reduce_linebreaks (bool): Whether to reduce mul-
tiple instances of double newlines to two
Returns: HTML-formatted typography-safe string
Return type: string
Example:
$string = auto_typography($string);
• nl2br_except_pre($str)
Example:
$string = nl2br_except_pre($string);
Parameters:
• $str (string): Input string
• $charset (string): Character set
Returns: String with decoded HTML entities
Return type: string
URL HELPER
The URL Helper file includes routines that make working
with URLs easier.
154 ◾ Mastering C++ Programming Language
Syntax:
$this->load->helper(’URL);
Available Functions
There are the following functions available:
• site_url([$uri = ’’[, $protocol = NULL]])
Parameters:
• $uri (string): URI string
• $protocol (string): Protocol, e.g. “http” or “https”
Returns: Site URL
Return type: string
Example:
echo site_url('news/local/123');
Parameters:
• $uri (string): URI string
• $protocol (string): Protocol, e.g. “http” or “https”
Returns: Base URL
Return type: string
Example:
echo base_url();
Example:
echo base url("blog/post/123");
• current_url()
156 ◾ Mastering C++ Programming Language
Example:
http://some-site.com/blog/comments/123
• index_page()
Returns: “index_page” value
Return type: mixed
Example:
echo index_page();
Parameters:
• $uri (string): URI string
• $title (string): Anchor title
• $attributes (mixed): HTML attributes
Working With Numbers and Spaces ◾ 157
Example:
echo anchor('news/local/123', 'News',
'title="Title"');
Parameters:
• $uri (string): URI string
• $title (string): Anchor title
• $attributes (mixed): HTML attributes
Returns: Pop-up hyperlink
Return type: string
• mailto($email, $title = ’’, $attributes = ’’)
Parameters:
• $email (string): E-mail address
• $title (string): Anchor title
• $attributes (mixed): HTML attributes
Returns: A “mail to” hyperlink
Return type: string
Example:
echo mailto('me@my-site.com', 'Click
Here to Contact Me');
158 ◾ Mastering C++ Programming Language
Parameters:
• $email (string): E-mail address
• $title (string): Anchor title
• $attributes (mixed): HTML attributes
Returns: A spam-safe “mail to” hyperlink
Return type: string
Parameters:
• $str (string): Input string
• $type (string): Link type (“email”, “url”, or “both”)
• $popup (bool): Whether to create popup links
Returns: Linkified string
Return type: string
Parameters:
• $str (string): Input string
• $separator (string): Word separator
• $lowercase (bool): Whether to transform the output
string to lower-case
Returns: URL-formatted string
Return type: string
Working With Numbers and Spaces ◾ 159
Example:
$title = " CSS Problems?";
$url_title = url_title($title);
• prep_url($str = ’’)
Parameters: $str (string)—URL string
Returns: Protocol-prefixed URL string
Return type: string
Parameters:
• $uri (string): URI string
• $method (string): Redirect method (“auto”, “loca-
tion”, or “refresh”)
• $code (string): HTTP Response code (usually 302
or 303)
Return type: void
XML HELPER
The XML Helper file includes methods that make dealing
with XML data easier.
Syntax:
$this->load->helper('xml');
Functions available
There are the following functions available:
• xml_convert($str[, $protect_all = FALSE])
Parameters:
• $str (string): the text string to be transformed
• $protect_all (bool): Whether all text that appears to
be a possible entity, rather than numbered entities,
such as &foo; should be protected.
Returns: string that has been translated to XML
Return type: string
• Ampersands: &
• Less than and more significant than characters: < >
• Single and double quotes: ‘ “
• Dashes: -
Example:
$string = '<p>Here is a paragraph & an
entity ({).</p>';
$string = xml_convert($string);
echo $string;
Working With Numbers and Spaces ◾ 161
STD::STRING
C++ includes a method for representing a series of charac-
ters as a class object in its definition. std:: string is the name
of this class. The String class holds characters as a series of
bytes, with the ability to retrieve a single-byte character.
Character Array vs. std:: string:
Example:
// C++ code to demonstrate the working of
// getline(), push_back() and
pop_back()
#include<iostream>
#include<string>
using namespace std;
int main()
{
// Declaring string
string str;
// Displaying string
cout << "The initial string is : ";
cout << str << endl;
Working With Numbers and Spaces ◾ 163
// Displaying string
cout << "The string after push_back
operation is : ";
cout << str << endl;
// Displaying string
cout << "The string after pop_back
operation is : ";
cout << str << endl;
return 0;
}
Output:
The initial string is: helloeveryone
The string after push_back operation
is: helloeveryone
The string after pop_back operation
is: helloeveryone'
164 ◾ Mastering C++ Programming Language
Functions of Capacity
Example:
// C++ code to demonstrate the working
of
// capacity(), resize() and
shrink_to_fit()
#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
// Initializing string
string str = " helloeveryone is for
college ";
Working With Numbers and Spaces ◾ 165
// Displaying string
cout << "Initial string: ";
cout << str << endl;
// Displaying string
cout << "String after resize
operation : ";
cout << str << endl;
Output:
Initial string: helloeveryone is for
college
String after resize operation:
helloeveryone
Capacity of string: 27
Length of the string:12
166 ◾ Mastering C++ Programming Language
Iterator Methods
Example:
// C++ code to demonstrate the working
of
// begin(), end(), rbegin(), rend()
#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
// Initializing string`
string str = "helloeveryone";
// Declaring iterator
std::string::iterator it;
// Displaying string
Working With Numbers and Spaces ◾ 167
return 0;
}
Output:
String using forward iterators:
helloeveryone
Reverse string using reverse iterators:
enoyreveolleh
Functions Manipulation
Example:
// C++ code to demonstrate the working
of
// copy() and swap()
#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
// Initializing 1st string
string str1 = " everyone is for
college ";
return 0;
Output:
The new copied character array is:
everyone
LIBRARY FORMATTING
The text formatting library is a secure and flexible replace-
ment for the printf routines. It’s meant to work with the
current C++ I/O streams library, reusing parts of its infra-
structure like overloaded insertion operators for user-
defined types.
Example:
std::string message = std::format("The
answer is {}.", 42);
Example:
string message = fmt::format("Answer
is {}.", 32);
printf new
– <
+ +
space space
# #
0 0
hh unused
h unused
l unused
ll unused
j unused (Continued)
174 ◾ Mastering C++ Programming Language
printf new
z unused
t unused
L unused
c c (optional)
s s (optional)
d d (optional)
i d (optional)
o o
x x
X X
u d (optional)
f f
F F
e e
E E
a a
A A
g g (optional)
G G
n unused
p p (optional)
The latter only allows for left and right alignment (the
default).
The example below utilizes center alignment and the
character ‘*’ as a fill character:
“***********centered***********” is the output of
fmt::format(“:*30”, “centered”); With printf, the same for-
matting is difficult to obtain.
EXTENSIBILITY
The API and the format string syntax are both designed
to be extensible. Users can add parsing and formatting
techniques for these types, and the mini-language can be
expanded to include user-defined types.
A replacement field in a format string has the follow-
ing general syntax:
SAFETY
Instead of using the cstdarg> method, formatting func-
tions use variadic templates. The type information is auto-
matically collected and given to formatters, ensuring type
safety and eliminating the need for many printf specifiers.
To avoid the typical printf buffer overflow problems, buffer
management is automated.
LOCALE SUPPORT
Many use cases do not necessitate internationalization
but do necessitate fast throughput when delivered via
a server, as mentioned in P0067R1: Elementary string
conversions. Various text-based interchange formats are
among them, such as JSON or XML. N4412: iostreams
Shortcomings underlines the importance of locale-inde-
pendent techniques for converting integers to strings
and floating-point values to strings. As a result, a user
should have easy discretion over employing locales dur-
ing formatting.
POSITIONAL ARGUMENTS
Because various languages have varied word orders, the
ability to alter formatting arguments is crucial for localiza-
tion. Consider the following scenario:
cout << "String '" << string << "' has "
<< length(string) << " characters\n";
PERFORMANCE
The performance of the formatting library was taken into
consideration when it was created. It aims to keep the
number of virtual function calls and dynamic memory
allocations per formatting operation as low as possible. It
should be feasible to eliminate them entirely by using an
appropriate API if formatting output can fit within a fixed-
size buffer created on the stack.
To this purpose, the fmt::basic buffer template is used
to represent a buffer abstraction. A buffer is a continuous
piece of memory that may be accessed directly and can
increase in size if necessary. During formatting, just one
virtual function, grow, has to be called, and it’s only when
the buffer isn’t big enough.
Locale-independent formatting is also more efficient to
implement than locale-aware formatting. However, rather
than improving performance, the former’s primary objec-
tive is to serve certain use cases.
178 ◾ Mastering C++ Programming Language
BINARY FOOTPRINT
Each formatting function that utilizes variadic templates
is a tiny inline wrapper over its non-variadic equivalent to
reducing binary code size. This wrapper uses fmt::make
args to construct an object representing an array of argu-
ment references, then calls the non-variadic function to
perform the real job. The format variadic function, for
example, uses the vformat variable.
If the number of arguments is minimal, several argu-
ment-type codes can be merged and given as a single integer
to a formatting function. Because the kinds of arguments
are known at build time, this can be an integer constant
for which no code is written except to store it according to
calling conventions.
This will produce a compact per-call binary code that
sets argument pointers and packed argument type codes
on the stack and executes a formatting function, assuming
a decent optimizing compiler.
Header <format> synopsis
namespace std {
namespace fmt {
Working With Numbers and Spaces ◾ 179
typedef basic_cstring_view<char>
cstring_view;
180 ◾ Mastering C++ Programming Language
class format_error;
arg-id is integer
integer is digit+
digit is '0'...'9'
Any character other than ‘{’ or ‘}’ can be used as the fill
character. The character after the fill character, which
must be one of the alignment possibilities, indicates a fill
character. The fill character and the alignment option are
presumed to be missing if the second character of format-
spec is not a valid alignment option.
The following are the definitions of the various align-
ment options:
Option Meaning
“<” Within the remaining space, forces the field to
be left-aligned.
“>” Within the available space, forces the field to be
right-aligned.
Working With Numbers and Spaces ◾ 183
Option Meaning
“+” This indicates that a sign should be used for
both positive as well as negative numbers.
“-” This indicates that a sign should be used only for
negative numbers (this is the default behavior).
space This indicates that a leading space should be
used on positive numbers and a minus sign on
negative numbers.
The “#” option forces the converter to use the other form.
For each kind, the alternative form is specified differently.
This option supports only integer and floating-point types.
This option adds the prefix “0b” (“0B”), “0”, or “0x” (“0X”)
to the output value for integers and to binary, octal, or
hexadecimal output. The case of the type specifier deter-
mines whether the prefix is lower-case or upper-case; the
prefix “0x” is used for the type “x”, whereas “0X” is used for
184 ◾ Mastering C++ Programming Language
the type “X”. The alternate form always causes the conver-
sion output to contain a decimal-point character, even if no
digits follow it, for floating-point values.
In most cases, a decimal-point character only appears
in the output of these conversions if a digit follows it.
Furthermore, trailing zeros are not eliminated from the
result for “g” and “G” conversions.
The decimal integer width defines the minimum field
width. If no field width is given, the content will decide the
field width.
Sign-aware zero-padding for numeric types is enabled
by preceding the width field with a zero (“0”) character.
This is the same as using the fill character “0” with the
alignment type “=”.
For a floating-point value formatted with “f” or “F”, the
precision is a decimal number that indicates how many dig-
its should be displayed after the decimal point. A floating-
point number is formatted with “g” or “G” before and after
the decimal point. The field determines the maximum field
size for non-number kinds, or how many characters will
be used from the field content. Integer, character, Boolean,
and pointer values are not permitted to be precise.
Finally, the type affects how the information is displayed.
The following string presentation types are available:
Type Meaning
“s” This is a string format. This is the default string
type, and it can be omitted.
none The same as “s”.
Working With Numbers and Spaces ◾ 185
Type Meaning
“c” Format for characters. This is the default charac-
ter type, and it can be removed.
none The same as “c”.
Type Meaning
“b” Binary is a kind of data. This function returns
an integer in base 2. The prefix “0b” is added
to the output value when the “#” option is used
with this type.
“B” Binary is a kind of data. This function returns
an integer in base 2. The prefix “0B” is added
to the output value when the “#” option is used
with this type.
“d” Integer in decimal form. Returns a number in
base ten.
“o” The format is octal. The number in base 8 is
returned.
“x” The hexadecimal system is used. The number
is written in base 16, with the digits above nine
written in lower case letters. The prefix “0x” is
added to the output value when the “#” option
is used with this type.
“X” The hexadecimal system is used. The number
is shown in base 16, with the digits above nine
represented by upper-case letters. The prefix
186 ◾ Mastering C++ Programming Language
Type Meaning
“a” Format for floating-point numbers in hexadeci-
mal. For numbers more than nine, prints the
number in base 16 with the prefix “0x” and
lower-case letters. The exponent is indicated by
the letter “p”.
“A” It’s the same as “a”, but with upper-case let-
ters for the prefix, numbers above nine, and an
exponent indication.
“e” Notation with exponents. The number is printed
in scientific notation, with the letter “e” indicat-
ing the exponent.
“E” Notation with exponents. It’s the same as “e”,
only the separator character is an upper-case
“E”.
“f” This is a fixed point. The number is shown as a
fixed-point number.
Working With Numbers and Spaces ◾ 187
Type Meaning
“p” Format for a pointer. This is the default pointer
type, and it can be omitted.
none The same as “p”.
FORMATTING FUNCTIONS
• template <class ...Args>
FORMATTING ARGUMENT
int
unsigned int
integral types larger than int
bool
Char
double
floating-point types larger than double
const char*
string_view
basic_string_view<Char>
const void*
• basic_arg();
Effects: Creates a basic_arg object that isn’t a refer-
ence to an argument.
Postcondition: !(*this).
Example:
auto uint_value = visit([](auto value) {
if constexpr
(is_unsigned_v<delctype(value)>)
return value;
return 0;
}, arg);
class arg_store;
class basic_args {
public:
typedef implementation-defined
size_type;
192 ◾ Mastering C++ Programming Language
basic_args() noexcept;
basic_arg<Context> operator[](size_
type i) const;
};
• basic_args() noexcept;
Effects: Constructs an empty basic_args object.
Postcondition: !(*this)[0].
• template <class ...Args>
basic_args(const arg_store<Context,
Args...>& store);
FORMATTING CONTEXT
• template <class Char>
class basic_context {
public:
typedef Char char_type;
typedef basic_args<basic_context>
args_type;
FORMATTING BUFFER
• template <class Char>
class basic_buffer {
public:
typedef implementation-defined
size_type;
virtual ~basic_buffer();
protected:
basic_buffer() noexcept;
FORMAT STRING
• template <class Char>
class basic_cstring_view {
public:
basic_cstring_view(const basic_
string<Char>& str);
basic_cstring_view(const Char* str);
USER-DEFINED TYPES
If a format string refers to a user-defined type object, as in:
X x;
string s = format("{}", x);
ERROR REPORTING
class format_error : public runtime_error
{
public:
explicit format_error(const string&
what_arg);
explicit format_error(const char*
what_arg);
};
Exploring C++
Functions
IN THIS CHAPTER
Example:
#include <iostream>
using namespace std;
class B {
public:
// A user-defined
// parameterized constructor
B(int y)
{
Exploring C++ Functions ◾ 199
int main()
{
// executes using defaulted
constructor
B b;
// uses parameterized constructor
B y(1);
return 0;
}
Output:
Parameterized constructor
Example:
class B {
public:
DELETED FUNCTION
Before C++ 11, the delete operator had just one purpose: to
deallocate dynamically allocated memory.
Another usage of this operator was introduced in the
C++ 11 standard: To stop a member function from being
used. The =delete; specifier is appended to the end of the
function definition to accomplish this.
An expressly deleted function is a member function whose
usage has been disallowed by using the “=delete” specifier.
This is generally done to implicit functions, though it is
not restricted to them. The following are some instances of
tasks where this functionality is proper:
• Disabling copy constructors
Example:
#include <iostream>
using namespace std;
class B {
public:
202 ◾ Mastering C++ Programming Language
int main()
{
B a1(1), b2(2), b3(3);
Example:
// delete operator using type
conversion
#include <iostream>
using namespace std;
Exploring C++ Functions ◾ 203
class B {
public:
B(int) {}
// deleted function.
// B(double) isn’t defined,
// the B(int) accept any double
value
// convert it to an int
B(double) = delete;
};
int main()
{
B B1(1);
class D
{
public:
D(D& d) = delete;
};
204 ◾ Mastering C++ Programming Language
Example:
// function as deleted
class D
{
public:
D();
};
WHAT IS LAMBDAS?
It’s a simple method to create a functor or anonymous
function object. It’s useful since we can define it locally and
call it or provide it as a parameter to a function.
Exploring C++ Functions ◾ 205
Example:
auto plus_one = [](const int value)
{
return value + 1;
};
assert(plus_one(2) == 3);
Example:
struct Oneplus
{
int op()(const int value) const
{
return val + 1;
}
};
206 ◾ Mastering C++ Programming Language
int main ()
{
Oneplus Oneplus;
assert(Oneplus(2) == 3);
return 0;
}
Example:
class P
{
public:
P(const int data) :
data(data) {}
int main ()
{
Exploring C++ Functions ◾ 207
P onePlus(1);
assert(Oneplus (2) == 3);
P twoPlus(2);
assert(twoPlus(2) == 4);
return 0;
}
Example:
auto p = [data=1](const int val)
{
return val + data;
};
assert(p(2) == 3);
208 ◾ Mastering C++ Programming Language
Example:
class P
{
public:
Plus(const int data) :
data(data) {}
int mainfun ()
{
Plus one_plus(1);
std::vector<int> test_data = {4, 2,
3, 1};
std::transform(test_data.begin(),
test_data.end(), test_data.begin(),
one_plus);
return 0;
}
Example:
auto return_one = [value=1](){ return
value; };
Example:
template<typename D>
int Plus(const int b, D fp)
{
return fp(a);
}
int main ()
{
auto one_plus = [value=1](const
int y) -> int
{
return y + val;
};
Exploring C++ Functions ◾ 211
return 0;
}
Example:
int Plusone(const int a,
std::function<int(const int)> fp)
{
return fp(a);
}
int main ()
{
auto one_plus = [value=1](const
int y) -> int
{
return y + value;
};
return 0;
}
Example:
#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
// Initializing array values
int arra[] = {20, 30, 15, 32,
54, 25};
Exploring C++ Functions ◾ 213
// Reversing
reverse(vect.begin(), vect.
end());
return 0;
}
214 ◾ Mastering C++ Programming Language
Output:
Vector is: 50, 40, 30, 20, 10, 5
Vector after sorting is: 5 10 20 30
40 50
Vector after reversing is: 50 40 230
15 10 5
Maximum element of vector is: 50
Minimum element of vector is: 5
Example:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int mainfun()
{
// array values
int arra[] = {30, 20, 5, 32, 24,
72, 51};
int num = sizeof(arra)/
sizeof(arra[0]);
vector<int> vect(arra, arra+num);
Exploring C++ Functions ◾ 215
return 0;
}
Output:
Occurrences of 32 in vector: 4
Example:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Initializing array values
int arra[] = {30, 20, 5, 32, 24,
72, 42, 45};
int num = sizeof(arr)/
sizeof(arra[0]);
vector<int> vect(arra, arra+num);
auto p = upper_bound(vect.
begin(), vect.end(), 20);
return 0;
}
Exploring C++ Functions ◾ 217
Output:
The lower bound is at position: 1
The upper bound is at position: 2
Example:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Initializing vector with array
values
int arra[] = {30, 20, 5, 32, 24,
72, 42, 45};
int num = sizeof(arra)/
sizeof(arra[0]);
vector<int> vect(arra, arra+num);
return 0;
}
Exploring C++ Functions ◾ 219
Output:
The vector is: 30 20 5 32 24 72
Vector after erasing element: 30 5
32 24 72 42 45
Vector before removing duplicate
occurrences: 5 24 30 32 42 45 72
Vector after deleting duplicates: 5
24 30 32 42 45 72
Example:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Initializing array values
int arra[] = {30, 20, 5, 32, 24,
72, 42, 45};
220 ◾ Mastering C++ Programming Language
Output:
Distance between first to max
element: 5
VARIADIC FUNCTION
Variadic functions take a variable number of arguments,
for example, std::printf.
An ellipsis comes after the list of parameters, e.g. int
printf(const char* format…);, which may be preceded by
an optional comma, to declare a variadic function. For
more information on the syntax, automated argument
conversions, and alternatives, see Variadic arguments.
The following library facilities are given to access the
variadic arguments from the function body:
Syntax:
temp(typename arg, typename... args)
return_type func_name(arg variable1,
args... variable2)
Example:
#include <iostream>
using namespace std;
print(var2...) ;
}
222 ◾ Mastering C++ Programming Language
// Driver code
int main()
{
print(2, 3, 4.14, "Pass any "
"number of arguments");
return 0;
}
Output:
2
3
4.14
Pass any number of arguments
Empty function and called at last
EXPRESSIONS
This section covers C++ expressions, which are collections
of operators and operands that serve one or more of the
following purposes:
The operands are used to calculate a value.
Objects or functions are designated.
Creating “unintended consequences” (Side effects are
any activities other than evaluating the expression, such as
changing an object’s value.)
Operators in C++ can be overloaded, and their seman-
tics can be customized. Their order of precedence and
the number of operands they accept, however, cannot be
changed. Without becoming overloaded, this section dis-
cusses the syntax and semantics of operators as supplied
by the language.
Exploring C++ Functions ◾ 223
Primary Expressions
Primary expressions serve as the foundation for more com-
plicated expressions. They can be literals, names, or names
with the scope-resolution operator qualified (::).
Syntax:
primary-exp
literal
this
name
:: name ( exp )
Example:
// expre_Primary_Expressions.cpp
class Examp
{
public:
Exploring C++ Functions ◾ 225
void Func();
void Func() const;
void Func() volatile;
};
Syntax:
Variadic templates employ an ellipsis in two ways. It
denotes a parameter pack to the left of the parameter name,
and it extends the parameter packs into distinct names to
the right of the parameter name.
template<typename… Arg> class class-name;
Example:
#include <iostream>
void print() {
cout << endl;
}
int main()
{
print(); // calls first overload
print(1); // calls second overload
print(20, 30);
print(200, 300, 400);
print("second", 3, "fourth", 4.14139);
}
Output:
1
20, 30
200, 300, 400
second, 3, fourth, 4.14139
Postfix Expressions
Primary expressions or expressions in which postfix oper-
ators follow a primary expression make up postfix expres-
sions. The following table lists the postfix operators.
Syntax:
void Func (int a) ; // Function
prototype
…
Func (4) ;
Example:
void func( long para1, double para2 );
int main()
{
long b = 2;
double c = 4;
• Bitwise OR (^)
• Bitwise OR (|)
• Operators that Logical
• Logical AND (&&)
• Logical OR (||)
• Assignment operators
• Assignment (=)
• Addition (+=)
• Subtraction (-=)
• Multiplication (*=)
• Division (/=)
• Modulus (%=)
• Left shift (<<=)
• Right shift (>>=)
• Bitwise AND (&=)
• Bitwise exclusive (^=)
• Bitwise inclusive (|=)
• Comma Operator (,)
• Bounds of an array
• Literals
• Constants of enumeration
FOLD EXPRESSIONS
Variadic templates are supported in C++11. These are
templates with an unlimited amount of template param-
eters. A parameter pack stores the arbitrary number.
Furthermore, using C++17, we may use a binary operator
to decrease a parameter pack directly. As a result, you may
use C++ to implement the Haskell functions foldl, foldr,
foldl1, and foldr1. Let’s have a look at how to turn a list
into a value.
Exploring C++ Functions ◾ 233
Example:
#include <iostream>
bool allVar(){
return true;
}
template<typename... Args>
bool all(Args... args) { return (...
&& args); }
int main(){
}
234 ◾ Mastering C++ Programming Language
Output:
allVar(true): true
all(true): true
allVar(true, true, true, false): false
all(true, true, true, false): false
Syntax:
template<typename... Args>
bool all(Args... args) { return (true
&& ... && args); }
Unary Folds
To fold parameter packs over a specified operator, unary
folds are utilised. Unary folds can be divided into two
types:
Syntax:
((Pack1 op Pack2) op ...) op PackN
236 ◾ Mastering C++ Programming Language
Syntax:
Pack1 op (... (Pack(N-1) op PackN))
Example:
template<typename... Ts>
int sum(Ts... args)
{
return (... + args); //Unary left
fold
//return (args + ...); //Unary
right fold
Binary Folds
Binary folds are unary folds with an additional parameter.
Binary folds may be divided into two types:
Syntax:
(((Value op Pack1) op Pack2) op ...)
op PackN
Exploring C++ Functions ◾ 237
Syntax:
Pack1 op (... op (Pack(N-1) op (PackN
op Value)))
Syntax:
template<typename... Cs>
int removeFrom(int num, Cs... args)
{
return (n - ... - args); //Binary
left fold
// Due to the lack of operator-
associativity, binary right fold
cannot be utilised.
}
Syntax:
template <class... Cs>
void print_all(std::ostream& os, Cs
const&... args) {
using expander = int[];
(void)expander{0,
238 ◾ Mastering C++ Programming Language
FRIEND KEYWORD
Classes that are well-designed encapsulate their func-
tionality, hiding their implementation while offering a
clean, well-documented interface. As long as the interface
remains unaltered, this enables redesign or modification.
Multiple classes that rely on each other’s implementa-
tion details may be necessary for a more complicated sce-
nario. Friend classes and functions allow these peers access
to each other’s details without endangering the specified
interface’s encapsulation and hiding information.
Function
Any function that is a buddy of a class or structure can be
declared. If a function is a class’s buddy, it has access to all
of the class’s protected and private members:
Example:
void friend_function();
void non_friend_function();
class Prihold {
public:
Prihold(int val) : private_
value(val) {}
private:
int pri_val;
// Declare function as a friend.
Exploring C++ Functions ◾ 239
void non_friend_function() {
Prihold ph(30);
// Compilation error
std::cout << ph.pri_val <<
std::endl;
}
void friend_function() {
// OK: friends may access private
values.
PrivateHolder ph(30);
std::cout << ph.pri_val <<
std::endl;
}
Method
class Access {
public:
void private_accesser();
};
class PriHold {
public:
PriHold(int val) : private_value(val)
{}
friend void
Accesser::private_accesser();
240 ◾ Mastering C++ Programming Language
private:
int pri_val;
};
void Accesser::private_accesser() {
PriHold ph(10);
std::cout << ph.pri_val << std::endl;
}
Friend Class
It is possible to declare a whole class as a friend. A buddy class
declaration indicates that every member of the friend has
access to the declaring class’s secret and protected members:
class Access {
public:
void private_accesser1();
void private_accesser2();
};
class PriHold {
public:
PriHold(int val) : private_value(val) {}
friend class Access;
private:
int pri_val;
};
void Accesser::private_accesser1() {
PrivateHolder ph(20);
// OK.
std::cout << ph.pri_val << std::endl;
}
Exploring C++ Functions ◾ 241
void Accesser::private_accesser2() {
PriHold ph(20);
std::cout << ph.pri_val + 1 << std::endl;
}
OVERLOADING A FUNCTION
Multiple functions with the same name exist in the same
area (known as scope) and differ only in their signature or
the arguments they take, known as function overloading.
Syntax:
void print(const std::string &str)
{
std::cout << "This is a string: " <<
str << std::endl;
}
Example:
std::string getValue()
{
return "hei";
}
int getValue()
{
return 0;
}
int y = getValue();
242 ◾ Mastering C++ Programming Language
Syntax:
template<typename T>
void f(T*) { }
template<typename T>
void f(T) { }
Exploring C++ Functions ◾ 243
Example:
{
auto pro = std::promise<std::
string>();
prod.join();
cons.join();
}
Example:
template<typename F>
auto async_deferred(F&& func) ->
std::future<decltype(func())>
{
auto tas = std::packaged_
task<decltype(func())()>(std::forwar
d<F>(function));
auto fut = task.get_future();
std::thread(std::move(task)).
detach();
return std::move(fut);
}
Example:
enum class fut_errc {
broken_promise = /*
task is no longer shared */,
future_already_retrieved = /*
answer was already retrieved */,
promise_already_satisfied = /*
answer was stored already */,
no_state = /*
access to a promise in non-shared
state */
};
• Inactive promise:
Example:
int tt()
{
std::promise<int> pr;
return 0;
}
int t()
{
std::promise<int> pr;
246 ◾ Mastering C++ Programming Language
Example:
#include <iostream>
using namespace std;
while((a<=mid)&&(c<=high))
{
if(num[a]<=num[j])
{
copy[b]=num[a];
h++;
}
else
{
Exploring C++ Functions ◾ 247
copy[b]=num[c];
c++;
}
b++;
}
if(a>mid)
{
for(d=c;d<=high;d++)
{
copy[b]=num[d];
b++;
}
}
else
{
for(d=a;d<=mid;d++)
{
copy[b]=num[d];
i++;
}
}
for(d=low;d<=high;d++)
swap(num[d],copy[d]);
}
{
merge_sort(low,mid,num);
});
auto fut2 = std::async(s
td::launch::deferred, [&]()
{
merge_sort(mid+1,high,
num) ;
});
fut1.get();
fut2.get();
merge(low,mid,high,num);
}
}
Syntax:
return_type func_name(func<return_type
fun_name(arg_list), other function
args)
Example:
#include <bits/stdc++.h>
using namespace std;
vector<string> Parse(vector<string> b,
function<bool(string)>
Parser)
{
vector<string> ans;
// Driver Code
int main()
{
vector<string> dict = { "hello",
"hoop",
"Hii", "for" };
// Results print
for (auto str : ans) {
cout << str << " ";
}
return 0;
}
Output:
Hoop Hii
Syntax:
map :: (c -> d) -> [c] -> [d]
map _ [ ] = [ ]
map f (y : ys) = f x : map f ys
IMPLEMENTATION MAP
A Map is a type of associative container that stores items in
a mapped order. There is a key value and a mapped value
for each element. The key values of two mapped values
cannot be the same.
Example:
#include<iostream>
#include <map>
#include <string>
using namespace std;
int main () {
map<char, int> m;
map<char, int>::iterator it;
m.insert (pair<char, int>('a', 20));
m.insert (pair<char, int>('b', 30));
m.insert (pair<char, int>('c', 40));
m.insert (pair<char, int>('d', 50));
cout<<"Size of the map: "<< m.size()
<<endl;
cout << "map contains:\n";
for (it = m.begin(); it != m.end();
++it)
cout << (*it).first << " => " <<
(*it).second << '\n';
for (char c = 'a'; c <= 'd'; c++) {
cout << "There is " << m.count(c)
<< " element with key " << c << ":";
map<char, int>::iterator it;
for (it = m.equal_range(c).first;
it != m.equal_range(c).second; ++it)
cout << ' ' << (*it).second;
cout << endl;
}
if (m.count('a'))
cout << "The key a is present\n";
else
cout << "The key a is not
present\n";
if (m.count('f'))
254 ◾ Mastering C++ Programming Language
Output:
Size of the map: 4
map contains:
a => 20
b => 30
c => 40
d => 50
There is 1 element with key a: 20
There is 1 element with key b: 30
There is 1 element with key c: 40
There is 1 element with key d: 50
The key a is present
The key f is not present
Size of the map: 3
Map contains:
a => 20
c => 40
d => 50
Exploring C++ Functions ◾ 255
Memory
Management
in C++
IN THIS CHAPTER
➢➢ Computer Memory
➢➢ Process Memory
➢➢ Objects in Memory
➢➢ Custom Memory Management
In this chapter, we’ll study what memory management is
and why it’s essential, as well as what memory manage-
ment operators are and why they’re helpful. Furthermore,
we will learn what dynamic memory allocation is, how to
MEMORY MANAGEMENT
In C++, we may allocate memory for a variable or an
array during runtime. Dynamic memory allocation is
the term for this. The compiler controls the memory
assigned to variables in other programming languages,
such as Java and Python. In C++, however, this is not
the case.
Memory Management in C++ ◾ 259
• It does not need the size of() operator since the size of
the data object is calculated automatically.
• It does not necessary to employ typecasting because
it delivers the right data type pointer.
260 ◾ Mastering C++ Programming Language
DELETE OPERATOR
We can deallocate the memory held by a variable that we
have declared dynamically after requiring it. The delete
Memory Management in C++ ◾ 261
delete pointerVar;
Example:
// declare a reference to an int
int* pointVari;
// allocate memory dynamically
pointVari = new int;
// assign value to the variable memory
*pointVari = 55;
// print the value stored in memory
cout << *pointVari;
// deallocate the memory
delete pointVari;
Source Code:
#include <iostream>
using namespace std;
int main() {
// int pointer declaration
int* pntInt;
// declare float
float* pntFloat;
// allocate memory dynamically
pntInt = new int;
pntFloat = new float;
// value assigning to the memory
*pntInt = 55;
*pntFloat = 55.55f;
cout << *pntInt << endl;
cout << *pntFloat << endl;
// deallocate memory
delete pntInt;
delete pntFloat;
return 0;
}
Output:
55
55.55
264 ◾ Mastering C++ Programming Language
Source Code:
// GPA of several students is stored
and shown in this program where n is
the num of students entered
#include <iostream>
using namespace std;
int main() {
int numb;
cout << "Enter total number of
students: ";
cin >> numb;
float* pntr;
// memory allocation
pntr = new float[numb];
return 0;
}
Output:
Enter total number of students: 5
Enter GPA
Student1: 4.4
Student2: 5
Student3: 3
Student4: 7
Student5: 8
Displaying GPA
Student1: 4.4
Student2: 5
Student3: 3
Student4: 7
Student5: 8
Source Code:
#include <iostream>
using namespace std;
class Stud {
int age;
public:
void getAge() {
cout << "Age: " << age << endl;
}
};
int main() {
// call getAge()
pntr->getAge();
return 0;
}
Memory Management in C++ ◾ 267
Output:
Age: 10
Syntax:
type variable = new
type(parameter_list);
Example:
#include <iostream>
using namespace std;
int main()
{
int *pntr; // integer pointer
pntr=new int; // allocating memory
Memory Management in C++ ◾ 269
Output:
Enter number:
30
Entered number 30
Example:
#include <iostream>
#include<stdlib.h>
using namespace std;
int main()
{
Output:
Enter the count:
5
Enter num:
12
Enter num:
5
Enter num:
7
Enter num:
9
Enter num:
8
Entered elements:
12
5
7
9
8
Syntax:
type reference_vari = new type name;
Example:
int *b;
p = (int *) malloc(sizeof(int))
PROCESS MEMORY
A process is a runnable programme that is loaded into
memory. A method is just a running program.
When a program is generated, it is nothing more than
a collection of bytes saved on the hard disc as a passive
object. When a program is double-clicked on Windows or
the name of the executable file is entered on the command
line, the program begins loading in memory and becomes
an active entity.
SWAPPING
A process must have resided in memory when it is run.
Swapping temporarily moves a process from main mem-
ory to secondary memory, which is faster than secondary
memory. More operations may be executed and fit into
memory at the same time, thanks to swapping. The trans-
ferred time is the most critical aspect of swapping, and the
overall time is proportional to the quantity of memory
swapped. Because if a higher priority process requests ser-
vice, the memory manager can swap out the lower priority
process and then load and run the higher priority process,
swapping is also known as roll-out, roll-in. After complet-
ing the higher priority activity, the lower priority process
swapped back into memory and resumed the execution
process.
Memory Allocation
Memory allocation must be allocated efficiently to achieve
optimal memory utilization. Divide memory into numer-
ous fixed-size divisions, each containing precisely one
process, is one of the simplest ways for allocating mem-
ory. The number of divisions determines the degree of
multiprogramming.
First Fit
In this case, the first accessible free slot satisfies the pro-
cess’s criteria.
280 ◾ Mastering C++ Programming Language
Best Fit
Assign the smallest hole that is large enough to process
requirements for the optimum fit. Unless the list is sorted
by size, we search the entire list for this.
Memory Management in C++ ◾ 281
Worst Fit
In the worst-case scenario, process the most enormous
available hole. This approach yields the most significant
remaining hole.
FRAGMENTATION
A Fragmentation is described as a tiny free hole created
when a process is loaded and deleted from memory after
execution. These holes can’t be allocated to new techniques
since they’re not merged or don’t meet the process’s mem-
ory requirements. We must decrease memory waste or frag-
mentation to accomplish a degree of multiprogramming.
There are two forms of fragmentation in operating systems:
282 ◾ Mastering C++ Programming Language
Internal Fragmentation
Internal fragmentation happens when the process is given
more memory blocks than requested. As a result, some
space remains, resulting in internal fragmentation.
External Fragmentation
We have a free memory block in external fragmentation,
but we can’t allocate it to process since the blocks aren’t
contiguous.
PAGING
Paging is a memory management method that eliminates
the need for physical memory allocation in contiguous
blocks. This technique allows a process’s physical address
space to be non-contiguous.
OBJECT IN C++
In C++, an object is a physical object such as a chair, auto-
mobile, pen, phone, laptop, etc.
An object is a state-and-behavior entity, to put it another
way. In this context, the terms “state” and “behaviour” are
interchangeable.
A runtime entity is produced during runtime.
284 ◾ Mastering C++ Programming Language
Syntax:
Class c1;
Example:
#include <iostream>
#include <memory>
void foo(std::shared_ptr<int> j)
{
(*j)++;
}
int main() {
// auto pointer = new int(20); //
illegal, no direct assignment
// Constructed a std::shared_ptr
Example:
auto pointer =
std::make_shared<int>(20);
auto pointer3 = pointer;
auto pointer4 = pointer;
int *g = pointer.get(); // no
increase of reference count
Memory Management in C++ ◾ 289
pointer3.reset();
std::cout << "reset pointer3:" <<
std::endl;
std::cout << "pointer.use_count() =
" << pointer.use_count() <<
std::endl;
std::cout << "pointer3.use_count() =
" << pointer2.use_count() <<
std::endl;
std::cout << "pointer4.use_count() =
" << pointer3.use_count() <<
std::endl;
pointer4.reset();
std::cout << "reset pointer4:" <<
std::endl;
std::cout << "pointer.use_count() =
" << pointer.use_count() <<
std::endl;
std::cout << "pointer3.use_count() =
" << pointer2.use_count() <<
std::endl;
std::cout << "pointer4.use_count() =
" << pointer3.use_count() <<
std::endl;
290 ◾ Mastering C++ Programming Language
int main() {
std::unique_ptr<Foo>
p1(std::make_unique<Foo>());
if (c1) c1->foo();
{
std::unique_ptr<Foo> c2(std::move(c1));
f(*c2);
if(c2) c2->foo();
if(c2) c2->foo();
std::cout << "c2 was destroyed" <<
std::endl;
}
if (c1) c1->foo();
#include <iostream>
#include <memory>
class C;
class D;
292 ◾ Mastering C++ Programming Language
class C {
public:
std::shared_ptr<D> pointer;
~C() {
std::cout << "A was destroyed" <<
std::endl;
}
};
class D {
public:
std::shared_ptr<C> pointer;
~D() {
std::cout << "D was destroyed" <<
std::endl;
}
};
int main() {
std::shared_ptr<C> c = std::make_
shared<C>(); std::shared_ptr<D> d =
std::make_shared<D>(); c->pointer = d;
d->pointer = c;
return 0;
}
Preprocessing
and Compilation
IN THIS CHAPTER
#include "HiWorld.h"
#include <iostream>
using namespace std;
void HiWorld::PrintHiWorld()
{
std::cout << "Hi World";
}
#include "HiWorld.h"
300 ◾ Mastering C++ Programming Language
int main()
{
HiWorld hello;
hello.PrintHiWorld();
return 0;
}
Syntax:
#ifdef MACRO
controlled text
#endif /* macroname */
Syntax:
ifndef macro_name
statement1;
.
.
statementN;
endif
Syntax:
#if macro_condition
statement
#elif macro_condition
statement
#else
statement
#endif
Syntax:
#line number "filename"
Syntax:
#error optional_error
WHAT IS ENABLE_IF?
Using boolean conditions to activate SFINAE is simple
using std::enable if. It is defined as follows:
Example:
template<typename Cont>
auto size2(Cont const& cont) ->
decltype( cont.size() );
// omitted implementation
template<typename Cont>
struct is_sizeable;
enable_if_all/enable_if_any
When a variable template pack is present in the template
parameters list, like in the following code snippet:
std::enable_if_t<std::conjunction_
v<custom_conditions_v<args>...>>* = nullptr>
void func(args &&...args) { //... };
is_detected
To generalise type trait generation, there are experimental
traits detected or, detected t, and is detected that are based
on SFINAE.
With the use of template parameters template <type-
name…>op and typename … args:
Example:
namespace detail {
template <class Def, class
AlwVoid,
template<class...>
class Op, class... args>
struct detector
{
using value_t =
std::false_type;
using type = Def;
};
nonesuc() = delete;
~nonesuc() = delete;
nonesuc(nonesuc const&) = delete;
void operator=(nonesuc const&) =
delete;
};
Example:
#include <algorithm>
#include <iterator>
namespace detail
{
// infinite types that inherit
from each other
template<std::size_d N>
struct pi : pi<N-1> {};
template<>
struct pi<0> {};
t.stable_sort();
}
template<typename D>
auto stable_sort(D& d, pick<1>)
-> decltype( d.sort(), void() )
{
d.sort();
}
enable_if Class
For SFINAE overload resolution, conditionally creates
an instance of a type. If and only if Condition is true, the
nested typedef enable if<Condition,Type>::type exists—
and is a synonym for Type.
Syntax:
template <bool B, class D = void>
struct enable_if;
Parameters:
• B: The value that determines if the resultant type exists
• D: If B is true, D is the type to instantiate
Remarks:
• Enable if<B, D> contains a nested typedef called
“type” that is a synonym for D if B is true
• Enable if<B, D> does not contain a nested typedef
called “type” if B is false
Syntax:
template <bool B, class D = void>
using enable_if_d = typename
enable_if<B,D>::type;
Preprocessing and Compilation ◾ 313
template <yours_stuff>
typename enable_if<yours_condition,
yours_return_type>::type
yoursfunction(args) {// ...
}
// It's more succinct using the
alias template.
template <yours_stuff>
enable_if_t<yours_condition,
yours_return_type>
yoursfunction(args) {// ...
}
template <yours_stuff>
yours_return_type_if_present
yoursfunction(args, enable_if_
t<yours condition, FOO> = BAR)
{// ...
}
314 ◾ Mastering C++ Programming Language
template <yours_stuff>
your_return_type_if_present
Preprocessing and Compilation ◾ 315
Example:
class B<int> {
public:
Preprocessing and Compilation ◾ 317
/* instantiated from
template < typename = typename
std::enable_if<
std::is_same< C, int >::value
>::type >
C foo() {
return 10;
}
*/
/* instantiated from
Making Preparations
For many years, developers have utilized the enable if class
template in combination with SFINAE to impose restric-
tions on template types.
The enable if template family is now part of the C++II
standard, and it works like this:
Syntax:
template <bool Test, class C = void>
struct enable_if
{ };
template<class C>
Preprocessing and Compilation ◾ 319
Example:
template <typename D,
typename = typename
std::enable_if<std::is_pod,D>::value,
D>:: type>
class pod_wrap
{
D value;
};
struct point
{
int a;
int b;
};
pod_wrap<int>
pod_wrap<point>
pod_wrap<std::string>
320 ◾ Mastering C++ Programming Language
Example:
template<typename D,
typename = typename std:: enable_if<
std::is_integral<D>:: value, D>::type>
auto mul (D const x, D const y)
{
return x * y;
}
auto k1 = mul(2,3);
auto k2 = mul(1.2,2.4);
{
D value;
};
template<typename D, typename =
Enablelf<std: : is_integral<D>>>
auto mul(D const x, D const y)
{
return x * y;
}
Example:
template <typename B>
void func (typename B: : data_type
const d)
{ std: :cout << "func" << std: :end1; }
ATTRIBUTES IN C++
Attributes are a fundamental element of contemporary
C++ that allow the programmer to provide extra infor-
mation to the compiler in order for the compiler to
impose constraints (conditions), optimize certain por-
tions of code, or generate specific code. In basic words,
an attribute is a note or annotation to the compiler that
gives more information about the code for the sake of
optimization and imposing specific constraints on it.
They were first introduced in C++11 and have remained
one of the greatest aspects of C++, evolving with each
subsequent version.
Example:
int d(int j)
{
if (j > 0)
return j;
else
return -1;
// code
}
Example:
int d(int j)[[expects:j > 0]]
{
// code
}
Example:
int d(int j)
{
switch (j) {
case 1:
[[fallthrough]];
[[likely]] case 2 : return 1;
}
return -1;
}
Example:
#include <iostream>
#include <string>
int main()
{
Syntax:
[[noreturn]] void g();
Example:
#include <iostream>
#include <string>
void h()
{
std::cout << "Code is intented to
reach";
}
int main()
{
d();
h();
}
Syntax:
[[deprecated("deprecation reason ")]]
// For Struct
struct [[deprecated]] D;
// For Functions
[[deprecated]] void g();
// For namespaces
namespace [[deprecated]] cs{}
// For variables
[[deprecated]] int y;
Example:
#include <iostream>
#include <string>
[[deprecated("Buffer overflow is a
risk")]] void gets(char* str)
{
std::cin.getline(st, 150);
str = std::string(st);
// new gets code
}
int main()
{
char c[150];
gets(c);
// std::string str;
// gets_n(str);
}
Syntax:
// Functions
[[nodiscard]] void g();
// Struct declaration
struct [[nodiscard]] my_struct{};
Example:
#include <iostream>
#include <string>
// Return value
[[nodiscard]] int g()
{
return 0;
}
class[[nodiscard]] my_class{};
int main()
{
int z{ 1 };
Syntax:
//Variables
[[maybe_used]] bool log_var = true;
//Funcs
[[maybe_unused]] void
log_without_warning();
//Func args
void f([[maybe_unused]] int x, int y);
Example:
#include <iostream>
#include <string>
int main()
{
Example:
void process_alert(Alert alert)
{
switch (alert) {
case Alert::Yellow:
evacuate();
// Compiler emits a warning here
case Alert::Red:
trigger_alarm();
case Alert::Blue:
record_alert();
return;
case Alert::Orange:
return;
}
}
Example:
int g(int j)
{
switch (j) {
case 1:
[[fallthrough]];
[[likely]] case 2 : return 1;
}
return 2;
}
Example:
struct Empty {
};
struct Y {
int j;
Empty e;
};
struct Z {
int j;
[[no_unique_address]] Empty d;
};
int main()
{
Preprocessing and Compilation ◾ 335
Syntax:
return_type func ( args...) [[expects
: precondition]]
Example:
#include <iostream>
ATTRIBUTES IN METADATA
The metadata characteristics describe the content’s creden-
tials. These qualifiers can be used to change how the mate-
rial is processed.
The metadata attributes are commonly used to filter
material based on their values. Another common applica-
tion is to mark content based on its values, for as by high-
lighting the impacted words in the output. Filtering is often
done using audience, platform, product, and otherprops,
and flagging is done with the same characteristics plus
rev. For example, designating stages in a job as optional
or mandatory, status and significance are utilized for tool-
specific or transform-specific behavior.
How To Do It
Use standard attributes to provide hints for the compiler
about various design goals:
Item get_value5()
{
return Item { };
}
get_value4()
get_value5()
namespace test
[debug] ] ;
• In C++11:
• A function with the [[noreturn]] property does
not return.
• The [[carries dependency]] property specifies that
under release-consume std: : memory order, the
dependency chain propagates in and out of the
function, allowing the compiler to omit superflu-
ous memory fence operations.
• In C++14:
• The attributes [[deprecated]] and [[deprecated
(“reason”)] ] indicate that the object declared
with these attributes is deprecated and should
not be utilized. These properties indicate that
the entity specified with these attributes is
deprecated and should no longer be utilized.
Classes, non-static data members, typedefs,
functions, enumerations, and template special-
izations can all benefit from these characteris-
tics. The reason string is a parameter that can
be left blank.
346 ◾ Mastering C++ Programming Language
• In C++17:
• The [ [fall through]] property indicates that a
switch statement’s fall-through across labels is
intended. The attribute must be placed on a sepa-
rate line before the case label.
• The [[nodiscard]] property specifies that a func-
tion’s return value cannot be disregarded.
• The [[maybe unused]] property indicates that an
object could be unused, but the compiler should
not issue a warning. Variables, classes, non-static
data members, enumerations, enumerators, and
typedefs can all have this feature.
Coroutines and
Lazy Generators
IN THIS CHAPTER
co_await
Now that that’s out of the way, C++20 provides us with a
new operator called co await. In general, the formula “co_
await a;” does the following:
Syntax:
task< > tcp_echo_server() {
char data[1045];
while (true) {
size_t nu = co_await socket.
async_read_some(buffer(data));
co_await async_write(socket,
buffer(data, nu));
}
}
Syntax:
generator<int> iota(int c = 0) {
while(true)
co_yield c++;
}
Syntax:
lazy<int> g() {
co_return 5;
}
Restrictions
Variadic arguments, simple return statements, and place-
holder return types are not allowed in coroutines (auto or
concept).
Coroutines aren’t allowed in constexpr functions, con-
structors, destructors, or the primary function.
Execution
• calls promise.
• co_awaits the outcome of final_suspend().
• If there is an uncaught exception at the end of the
coroutine, it does the following:
• The exception is caught, and promise is called.
• From within the catch-block, call unhandled_
exception ().
• calls promise.
• final_suspend() and co_awaits the result; resuming
a coroutine from this point is undefined behavior.
• When a coroutine state is destroyed, it performs
the following:
• The promise object’s destructor is called.
• Calls the function parameter copies’ destructors.
• To release the memory occupied by the coroutine
state, call operator delete.
• Returns control to the caller.
HEAP ALLOCATION
Coroutine state is allocated on the heap using the non-
array operator new.
If a class-level replacement is defined in the Promise
type, it will be utilized; otherwise, the new global operator
will be used.
Those arguments will be provided to operator new if the
Promise type provides a placement form of operator new
Coroutines and Lazy Generators ◾ 355
Promise
We can add field value_ to this type and transfer val-
ues from the coroutine to our main function because
we know the coroutine state contains an instance of
promise type. How do we obtain access to the prom-
ise type? This isn’t too difficult in the main function. We
may maintain our coroutine handle as a std::coroutine_
handle<ReturnObject3::promise_type> instead of con-
verting it to a std::coroutine_handle<>. The promise type&
that we require will be returned by the function promise()
on this coroutine handle.
Example:
struct ReturnObject4 {
struct promise_type {
unsigned value_;
ReturnObject4 get_return_object()
{
return ReturnObject4 {
.a_ =
std::coroutine_handle<promise_
type>::from_promise(*this)
};
}
std::suspend_never initial_
suspend() { return {}; }
std::suspend_never final_suspend()
noexcept { return {}; }
void unhandled_exception() {}
};
std::coroutine_handle<promise_type>
a_;
operator std::coroutine_
handle<promise_type>() const { return
a_; }
};
358 ◾ Mastering C++ Programming Language
ReturnObject4
Counter4()
{
auto pp = co_await GetPromise<Return
Object4::promise_type>{};
void
main4()
{
std::coroutine_
handle<ReturnObject4::promise_type> a
= counter3();
ReturnObject4::promise_type &promise
= a.promise();
for (int c = 0; c < 4; ++c) {
std::cout << "counter3: " <<
promise.value_ << std::endl;
a();
}
a.destroy();
}
It’s worth noting that our promise object copies i’s value
from the coroutine into promise type::value_ before pass-
ing it to the main function. We could have made value_an
unsigned * and returned a reference to the variable I within
counter3 in a somewhat confusing way. Because the corou-
tine’s local variables are stored in the heap’s coroutine state
Coroutines and Lazy Generators ◾ 359
co_await
The unary operation co_await suspends a coroutine and
hands control back to the caller. Its operand is an expres-
sion whose type either defines operator co_await or can be
converted to such a type using the current coroutine’s type
conversion Promise::await_transform.
360 ◾ Mastering C++ Programming Language
co_wait expr
Example:
#include <coroutine>
#include <iostream>
#include <stdexcept>
#include <thread>
362 ◾ Mastering C++ Programming Language
auto switch_to_new_thread(std::jthread&
out) {
struct await {
std::jthread* a_out;
bool await_ready() { return false; }
void await_suspend(std::coroutine_
handle<> h) {
std::jthread& out = *a_out;
if (out.joinable())
throw std::runtime_
error("Output jthread not empty");
out = std::jthread([k] {
k.resume(); });
struct taskk{
struct promise_type {
taskk get_return_object() { return
{}; }
std::suspend_never initial_
suspend() { return {}; }
std::suspend_never final_suspend()
noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
Coroutines and Lazy Generators ◾ 363
taskk resuming_on_new_
thread(std::jthread& out) {
std::cout << "Coroutine started: "
<< std::this_thread::get_id() << ’\n’;
co_await switch_to_new_thread(out);
// awaiter destroyed
std::cout << "Coroutine resumed: "
<< std::this_thread::get_id() << ’\n’;
}
int main() {
std::jthread out;
resuming_on_new_thread(out);
}
co_yield
Getting a coroutine’s promise object is so hard because the
C++ authors had one specific use case in mind and planned
for that rather than the broader situation. Returning values
from coroutines, on the other hand, is a valuable use case. To
that purpose, the language includes the co_yield operator.
Yield-expression gives the caller a value and stops
the current coroutine: It is a fundamental component of
resumable generator functions:
Syntax:
co_yield expr
co_yield braced-init-lists
equivalent to:
co_await promise.yield_value(expression)
Example:
struct ReturnObject5 {
struct promise_type {
unsigned value_;
ReturnObject5 get_return_object() {
return {
. a_ =
std::coroutine_handle<promise_
type>::from_promise(*this)
};
}
std::suspend_never initial_
suspend() { return {}; }
std::suspend_never final_suspend()
noexcept { return {}; }
void unhandled_exception() {}
std::suspend_always yield_
value(unsigned value) {
value_ = value;
return {};
}
};
std::coroutine_handle<promise_type>
h_;
};
ReturnObject5
Counter5()
{
for (unsigned c = 0;; ++c)
co_yield c;
}
366 ◾ Mastering C++ Programming Language
void
main5()
{
auto h = counter5().a_;
auto &promise = a.promise();
for (int c = 0; c < 3; ++c) {
std::cout << "counter5: " <<
promise.value_ << std::endl;
a();
}
a.destroy();
}
co_return Operator
After reading the first three integers, our main function simply
deleted the coroutine state, resulting in an endless stream of
integers. What if our coroutine only wishes to create a certain
amount of values before indicating the end of the coroutine?
C++ includes a new co_return operator to mark the end
of a coroutine. A coroutine can communicate that it is fin-
ished in one of three ways:
Example:
struct ReturnObject6 {
struct promise_type {
unsigned value_;
~promise_type() {
std::cout << "promise_type
destroyed" << std::endl;
}
ReturnObject6 get_return_object() {
return {
. a_ =
std::coroutine_handle<promise_
type>::from_promise(*this)
};
}
std::suspend_never initial_
suspend() { return {}; }
std::suspend_always final_suspend()
noexcept { return {}; }
void unhandled_exception() {}
368 ◾ Mastering C++ Programming Language
std::suspend_always yield_
value(unsigned value) {
value_ = val;
return {};
}
void return_void() {}
};
std::coroutine_handle<promise_type>
h_;
};
ReturnObject6
Counter6()
{
for (unsigned c = 0; c < 3; ++c)
co_yield c;
// falling off end of function =>
promise.return_void();
// (co_return value; => promise.
return_value(val);)
}
void
main6()
{
auto a = counter5().a_;
auto &promise = h.promise();
while (!a.done())
std::cout << "counter6: " <<
promise.value_ << std::endl;
a();
}
a.destroy();
}
Coroutines and Lazy Generators ◾ 369
Syntax:
{
promise-type promise promise-
constructor-args ;
try
{
co_await promise.initial_
suspend() ;
function-body
}
catch ( ..... )
{
if
(!initial-await-resume-called)
throw ;
promise.unhandled_
exception() ;
}
final-suspend :
co_await promise.final_suspend() ;
}
Example:
void
g()
{
std::vector<std::coroutine_handle<>>
coros =
{ mkCoroutineA(), mkCoroutineB() };
try {
for (int c = 0; c < 3; ++c)
for (auto &c : coros)
if (!a.done())
a();
}
catch (...) {
for (auto &c : coros)
a.destroy();
throw;
}
for (auto &a : coros)
a.destroy();
}
Example:
template<typename D>
struct Generator {
struct promise_type;
using handle_type =
std::coroutine_handle<promise_type>;
struct promise_type {
D value_;
std::exception_ptr exception_;
Generator get_return_object() {
return
Generator(handle_type::from_
promise(*this));
}
std::suspend_always initial_
suspend() { return {}; }
std::suspend_always final_suspend()
noexcept { return {}; }
void unhandled_exception() {
exception_ = std::current_exception(); }
template<std::convertible_to<D>
From>
374 ◾ Mastering C++ Programming Language
std::suspend_always yield_
value(From &&from) {
value_ = std::forward<From>(from);
return {};
}
void return_void() {}
};
handle_type a_;
Generator(handle_type a) : a_(a) {}
~Generator() { a_.destroy(); }
explicit operator bool() {
fill();
return !a_.done();
}
D operator()() {
fill();
full_ = false;
return std::move(a_.promise().
value_);
}
private:
bool full_ = false;
void fill() {
if (!full_) {
a_();
if (a_.promise().exception_)
std::rethrow_exception(h_.
promise().exception_);
full_ = true;
}
}
};
Coroutines and Lazy Generators ◾ 375
Generator<unsigned>
counter7()
{
for (unsigned c = 0; c < 4;)
co_yield c++;
}
void
main7()
{
auto gen = counter7();
while (gen)
std::cout << "counter7: " << gen()
<< std::endl;
}
Greedy Generator
The software that follows is as simple as possible. The func-
tion getNumbers returns all integers from start to finish,
which inc has incremented. The beginning must be smaller
than the ending, and the increment must be positive.
Example:
#include <iostream>
#include <vector>
return numb;
int main() {
Lazy Generator
Example:
#include <iostream>
#include <vector>
generator<int> generatorForNumb(int
begin, int inc = 2) {
co_yield c;
}
}
int main() {
std::cout << std::endl;
const auto numb=
generatorForNumb(-5);
for (int c= 1; c <= 30; ++c)
std::cout << numb << " ";
std::cout << "\n\n";
for (auto n: generatorForNumb(0,
4)) std::cout << n << " ";
std::cout << "\n\n";
}
Example:
std::generator<int> fib (int maxi) {
co_yield 0;
auto c = 0, d = 1;
}
378 ◾ Mastering C++ Programming Language
Motivation
Coroutine support in C++ 20 was quite limited.
Synchronous generators are standard for coroutines that
would be impossible to implement without the technology
described in this work. Writing an efficient and appro-
priately behaved recursive generator; thus, the standard
should provide one.
Design
While the proposed std::generator interface is straightfor-
ward, there are a few considerations worth noting.
Header
There are several places where the generator class may be
placed.
template<std::ranges::input_range Rng1,
std::ranges::input_range Rng2> generator<
std::tuple<std::ranges::range_reference_
t<Rng1>,
std::ranges::range_reference_t<Rng2>,
std::tuple<std::ranges::range_value_type_
t<Rng1>,
std::ranges::range_value_type_t<Rng2>>>
zip(Rng1 R1, Rng2 R2) {
auto iti1 = std::ranges::begin(R1);
auto iti2 = std::ranges::begin(R2);
auto endi1 = std::ranges::end(R1);
auto endi2 = std::ranges::end(R2); while
(it1 != endi1 && it2 != endi2) {
380 ◾ Mastering C++ Programming Language
std::generator<std::string_view,
std::string> strings() {
co_yield "start";
std::string st;
for (auto stv : string_views()) { st = stv;
st.push_back('!'); co_yield st;
}
co_yield "end";
}
iteration! auto v =
std::to<vector>(strings());
Recursive Generator
A “recursive generator” is a coroutine that allows to directly
co_yield a generator of the same type to emit its elements
as elements of the current generator.
Coroutines and Lazy Generators ◾ 381
Example:
Recursive usage of a generator is also
possible.
struct Trees {
Trees* left; Trees* right; int val;
};
co_yield y;
}
}
generator<int> might_throw() {
co_yield 0;
throw some_error{};
}
generator<int> nested_ints() {
try
{
co_yield elements_of(might_throw());
} catch (const some_error&) {}
co_yield 1;
}
// nested_ints() is semantically
equivalent
generator<int> manual_ints() {
try {
for (int y : might_throw()) { co_yield y;
}
} catch (const some_error&) {} co_yield 1;
}
void consumer() {
for (int y : nested_ints()) {
std::cout << y << " ";
}
elements_of
When a nested generator type is convertible to the value
type of the current generator, elements_of is a utility func-
tion that prevents ambiguity.
Example:
generator<int> g()
{
co_yield 22;
generator<any> h()
{
co_yield g();
}
generator<int> g()
{
std::vector<int> y = /*... */;
co_yield elements_of(y);
}
Coroutines and Lazy Generators ◾ 385
SYMMETRIC TRANSFER
With the symmetric transfer, the recursive form may be
accomplished quickly. This functionality was previously pro-
vided in a separate recursive_generator type in [CppCoro].
However, owing to HALO improvements and symmetric
transfer, it looks that a single type is quite efficient. That func-
tionality comes at a memory cost of three additional pointers
per generator. Given the current state of compiler support for
coroutines, estimating the runtime cost of our approach is chal-
lenging. Our testing, however, reveals no discernible difference
between a generator and a recursive_generator, sometimes
known as non_recursively. It’s worth mentioning that the sug-
gested approach ensures the possibility of HALO optimizations.
While we believe that a single generator type is adequate
and provides a superior API, there are three alternatives:
• Support for recursive calls in a single generator type
(this proposal).
• A recursive generator type that may return values
from either a recursive generator or a generator. That
might result in minimal performance gains while
using the same amount of RAM.
• A recursive generator type that can only return val-
ues from other recursive_- generator types.
recursive_generator<int> h()
{
for (int y : g()) co_yield y;
}
generator<string_view> g()
{
co_yield std::string(); // error
}
Example:
std::generator<int, int,
std::allocator<std::byte>>
stateless_examples()
{
co_yield 35;
}
388 ◾ Mastering C++ Programming Language
my_allocator<std::byte> alloc;
input_range auto rng = allocator_
examples<my_allocators<std::byte>>(std
::allocator_arg, alloc);
struct Sampless
{
Sampless() = delete;
static Windows::Foundation::IAsyncAction
CopyAsync();
};
namespace Window::Foundation
{
struct IAsyncAction;
template <typename Prog>
Coroutines and Lazy Generators ◾ 393
struct IAsyncActionWithProgress;
template <typename Result>
struct IAsyncOperation;
template <typename Res, typename Prog>
struct IAsyncOperationWithProgress;
}
Samples::CopyAsync().get();
It’s crucial to remember that the get method will block the
caller thread until the async function completes. As a result,
using the get method on a UI thread is not recommended
since it may cause the program to become sluggish. If we try to
do so in an unoptimized build, an assertion will fire. The get
method is excellent for console apps or background threads
if we don’t want to utilize a coroutine for whatever reason.
The get function will return any result to the caller after
the async procedure has been completed. The return type
for IAsyncAction and IAsyncActionWithProgress is void.
That could be beneficial for an async method that begins a
file-copy operation but not so much for an async method
that reads a file’s contents.
To the example, let’s add another async method:
struct Sampless
{
Sampless() = delete;
static Windows::Foundation::IAsyncAction
CopyAsync();
static Windows::Foundation::IAsyncOperat
ion<hstring> ReadAsync();
};
Sampless::CopyAsync().get();
hstring result = Sampless::ReadAsync().get();
Coroutines and Lazy Generators ◾ 395
Example:
auto async = ReadAsync();
if (async.Status() ==
AsyncStatus::Completed)
{
auto res = async.GetResults();
printf("%ls\n", result.r_str());
}
Implementing IAsyncAction:
struct MyAsync: implement<MyAsync,
IAsyncAction, IAsyncInfo>
{
// IAsyncInfo member
Uint42_t Id() cons;
AsyncStatus Status() cons;
HRESULT ErrorCode() cons;
void Cancel() cons;
void Close() cons;
// IAsyncAction member
void Completed(AsyncActionCompletedHand
ler const& handler) cons;
AsyncActionCompletedHandler Completed()
cons;
void GetResults() cons;
};
IAsyncAction CopyAsync()
{
co_return;
}
IAsyncAction CopyAsync()
{
co_return;
}
int mainfun()
402 ◾ Mastering C++ Programming Language
{
IAsyncAction async = CopyAsync();
async.get();
}
IAsyncAction Async()
{
co_return;
}
int mainfun()
{
IAsyncAction async = Async();
assert(async.Status() ==
AsyncStatus::Completed);
}
hstring m_cache;
IAsyncOperation<hstring> ReadAsync()
{
if (m_cache.empty())
{
// cache value and download
}
co_return m_cache;
}
int mainfunc()
{
hstring mesg = ReadAsync().get();
printf("%ls\n", mesg.c_str());
}
IAsyncAction MainAsync()
{
hstring res = co_await ReadAsync();
printf("%ls\n", res.c_str());
}
int main()
{
MainAsync().get();
}
put in now will pay off later since you will have already
completed a substantial portion of the job.
In exchange for your investment, you will have access to
a wide selection of career possibilities in a variety of sec-
tors. C++’s long-standing popularity is reflected in the high
number of job openings. Not only are many new applica-
tions written in C++, but the large numbers of existing
systems that use the language need the hiring of coders to
maintain them current and updated.
Furthermore, because C++ applications require a huge
amount of code to scale, some organizations demand quite
big development teams (relative to other languages). As a
result, skilled C++ programmers will always be in demand.
Finally, many coders are likely to learn C++ because of the
fascinating array of career prospects in sectors such as
game development. These are difficult areas to enter into,
requiring a lot of devotion and hard work.
Job openings in C++: According to the Developer
Survey, C++ is the sixth most popular programming lan-
guage overall, with 19.4% of those polled saying they use it.
Other C languages are also popular (which any C++ devel-
oper will have a good start on learning). C# (a Microsoft
language based on C++ that seeks to integrate the best of
Visual Basic) is fourth with 30.9% total use, and C++’s pre-
decessor is seventh with 15.5%.
Gooroo, a skills analytics platform, records around
5,900 C++ jobs posted every month in the United States
(approximately 10,000 globally), with an average pay of
more than £100,000 in the United States (just over $80,000
globally). Based on experience, an average C++ salary
PayScale also has an interesting graph that illustrates how
Appraisal ◾ 409
C++’S APPLICATIONS
• C++ Games: C++ is fast and near to the hardware. It
can quickly handle resources, offer procedural pro-
gramming over CPU-intensive tasks, and it is close
to the hardware. It can handle the complexity of 3D
games and has several networking levels. Because of
these advantages, it is the preferred platform for cre-
ating gaming systems and game development suites.
• C++ can easily create most GUI-based and desktop
apps since it offers all of the necessary capabilities.
Adobe Photoshop, for example.
• Database Management Software: It’s also utilized in
the development of database management software.
MySQL and Postgres, the two most popular data-
bases, are developed in C++.
• Operating Systems: C++ is an appropriate program-
ming language for building operating systems since it
is tightly typed and quick. In addition, C++ includes
a large set of system-level functions that aid in the
development of low-level applications.
A B
AAA games, 407 Base and derived classes, 61–62
Abstraction, 7, 13–14, 93–94, Base class, 61
99–100 Binary footprint, 178
benefits of, 94–95 Binary operators in expressions,
kinds of, 94 230–231
Access control, inheritance and, Bitwise operators, 37
63–64 Blocks, 19
Actual arguments, 227–228 Boolean data type, 132
Applications of C++, 411 Boolean Literals, 30
Arithmetic operators, 35 Boost library, 123
Arrays, 48–49
character array, 161
C
new and delete operators,
264–265 C++ and C# characteristics,
Assignment operators, 37 differences between,
Async completion, meeting the 338
needs of, 395–400 C++ compilers, 4
Asynchronous operations, C++ console application project,
classes for, 248 16
Async interfaces, 400–404 C++11, 324, 336–338, 345
Attributes in C++, 324 C++14, 345
in metadata, 339–341 C++17, 346
purpose of, 324–336 C++20, 349
Auto storage class, 33 Callback, function of, 208–210
Awaiter.await_ready(), 360–361 C and C++, 4
417
418 ◾ Index
F Function name, 43
Function overloading, 241
Features of C++, 6
Functions in C++, 42
File handling in C++, 88–92
arguments for functions,
Fixed partition allocation, 279
44–45
best fit, 280
declarations of, 44
first fit, 279–280
formal parameters, 44
worst fit, 281
making a function call, 44
Floating Point data type, 132,
parameters default values,
134–135
45–46
Floating-point literals, 29
Function template make_args,
Fold expressions, 232
193
binary folds, 236–237
Function templates
comma, folding over, 237–238
legitimate overloading of, 242
options, 234–235
overloading of, 242
unary folds, 235–236
Functor/function object,
Formal arguements, 227–229
205–207
Format specification mini-
lambdas vs., 207–208
language, 181–187
Format string, 195
G
Format string syntax, 180–181
Formatting argument, 188–190 Generators, 371
Formatting argument visitation, design, 378
190–191 elements_of, 384
Formatting buffer, 194–195 generic generators, 371–375
Formatting context, 193–194 greedy generator, 375–376
Formatting functions, 187–188 header, 379
Fragmentation, 281 lazy generator, 376–377
external, 282 motivation, 378
internal, 282 recursive generator, 380–383
Free() function, 270 std::generator, 377–378
Friend keyword, 238 value type, 379–380
friend class, 240–241 Generic generators, 371–375
function, 238–239 Get() function, 288
method, 239–240 GetResults method, 396–397
fstream, 85 Global level variables, 27–28
Function arguments, structures initializing, 28
as, 117–119 Gooroo, 408
Function body, 43 Greedy generator, 375–376
422 ◾ Index