0% found this document useful (0 votes)
8 views115 pages

C++ QB Ans

Uploaded by

zs918518
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views115 pages

C++ QB Ans

Uploaded by

zs918518
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

1) Explain various datatypes and qualifiers in C++.

Ans:
All variables use data type during declaration to restrict the type of data to be
stored. Therefore, we can say that data types are used to tell the variables the
type of data they can store. Whenever a variable is defined in C++, the
compiler allocates some memory for that variable based on the data type with
which it is declared. Every data type requires a different amount of memory.
C++ supports a wide variety of data types and the programmer can select the
data type appropriate to the needs of the application. Data types specify the
size and types of values to be stored. However, storage representation and
machine instructions to manipulate each data type differ from machine to
machine, although C++ instructions are identical on all machines.
C++ supports the following data types:
1. Primary or Built-in or Fundamental data type
2. Derived data types
3. User-defined data types

Data Types in C++ are Mainly Divided into 3 Types:


1. Primitive Data Types: These data types are built-in or predefined data
types and can be used directly by the user to declare variables. example: int,
char, float, bool, etc. Primitive data types available in C++ are:
● Integer
● Character
● Boolean
● Floating Point
● Double Floating Point
● Valueless or Void
● Wide Character

2. Derived Data Types: Derived data types that are derived from the primitive
or built-in datatypes are referred to as Derived Data Types. These can be of
four types namely:
● Function
● Array
● Pointer
● Reference

3. Abstract or User-Defined Data Types: Abstract or User-Defined data


types are defined by the user itself. Like, defining a class in C++ or a structure.
C++ provides the following user-defined datatypes:
● Class
● Structure
● Union
● Enumeration
● Typedef defined Datatype

Primitive Data Types


● Integer: The keyword used for integer data types is int. Integers
typically require 4 bytes of memory space and range from -2147483648 to
2147483647.
● Character: Character data type is used for storing characters. The
keyword used for the character data type is char. Characters typically require
1 byte of memory space and range from -128 to 127 or 0 to 255.
● Boolean: Boolean data type is used for storing Boolean or logical
values. A Boolean variable can store either true or false. The keyword used for
the Boolean data type is bool.
● Floating Point: Floating Point data type is used for storing
single-precision floating-point values or decimal values. The keyword used for
the floating-point data type is float. Float variables typically require 4 bytes of
memory space.
● Double Floating Point: Double Floating Point data type is used for
storing double-precision floating-point values or decimal values. The keyword
used for the double floating-point data type is double. Double variables
typically require 8 bytes of memory space.
● void: Void means without any value. void data type represents a
valueless entity. A void data type is used for those function which does not
return a value.
● Wide Character: Wide character data type is also a character data type
but this data type has a size greater than the normal 8-bit data type.
Represented by wchar_t. It is generally 2 or 4 bytes long.
● sizeof() operator: sizeof() operator is used to find the number of bytes
occupied by a variable/data type in computer memory.

Qualifier:

A qualifier is a token added to a variable that adds an extra quality, such as


specifying volatility or constant-ness to a variable. It acts like an adjective for a
variable. With or without a qualifier, the variable still holds the same amount of
memory, and each bit has the same interpretation or contribution to the state/value.
Qualifiers specify how it can be accessed or where it is stored. There are three
qualifiers in C++. These are:
const It defines that the type is constant.

volatile It defines that the type is volatile.

mutable It applies to non-static class members of the non-reference


non-const type. Mutable members of const classes are modifiable.

2) Explain the bit wise operators with example.


Ans:
In C++, bitwise operators perform operations on integer data at the
individual bit-level. These operations include testing, setting, or shifting the
actual bits.
Here is a list of 6 bitwise operators included in C++.

Operator Description

& Bitwise AND Operator

| Bitwise OR Operator

^ Bitwise XOR Operator

~ Bitwise Complement Operator

<< Bitwise Shift Left Operator


>> Bitwise Shift Right Operator

These operators are necessary because the Arithmetic-Logic Unit (ALU)


present in the computer's CPU carries out arithmetic operations at the
bit-level.

Note: Bitwise operators can only be used alongside char and int data
types.

1. C++ Bitwise AND Operator


The bitwise AND & operator returns 1 if and only if both the operands are 1.
Otherwise, it returns 0.

The following table demonstrates the working of the bitwise AND operator.
Let a and b be two operands that can only take binary values i.e. 1 and 0.

a b a&b

0 0 0

0 1 0

1 0 0
1 1 1

Note: The table above is known as the "Truth Table" for the bitwise AND
operator.

Let's take a look at the bitwise AND operation of two integers 12 and 25:

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

//Bitwise AND Operation of 12 and 25

00001100
& 00011001
_________
00001000 = 8 (In decimal)

Example 1: Bitwise AND


#include <iostream>
using namespace std;

int main() {
// declare variables
int a = 12, b = 25;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a & b = " << (a & b) << endl;

return 0;
}

Run Code

Output

a = 12
b = 25
a & b = 8

In the above example, we have declared two variables a and b. Here, notice
the line,

cout << "a & b = " << (a & b) << endl;

Here, we are performing bitwise AND between variables a and b.

2. C++ Bitwise OR Operator


The bitwise OR | operator returns 1 if at least one of the operands is 1.
Otherwise, it returns 0.

The following truth table demonstrates the working of the bitwise OR


operator. Let a and b be two operands that can only take binary values i.e.
1 or 0.

a b a|b

0 0 0

0 1 1

1 0 1

1 1 1

Let us look at the bitwise OR operation of two integers 12 and 25:


12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
_________
00011101 = 29 (In decimal)

Example 2: Bitwise OR
#include <iostream>

int main() {
int a = 12, b = 25;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a | b = " << (a | b) << endl;

return 0;
}

Run Code

Output

a = 12
b = 25
a | b = 29

The bitwise OR of a = 12 and b = 25 gives 29.

3. C++ Bitwise XOR Operator


The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1.
However, if both the operands are 0, or if both are 1, then the result is 0.
The following truth table demonstrates the working of the bitwise XOR
operator. Let a and b be two operands that can only take binary values i.e.
1 or 0.

a b a^b

0 0 0

0 1 1

1 0 1

1 1 0

Let us look at the bitwise XOR operation of two integers 12 and 25:

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
_________
00010101 = 21 (In decimal)

Example 3: Bitwise XOR


#include <iostream>

int main() {
int a = 12, b = 25;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a ^ b = " << (a ^ b) << endl;
return 0;
}

Run Code

Output

a = 12
b = 25
a ^ b = 21

The bitwise XOR of a = 12 and b = 25 gives 21.

4. C++ Bitwise Complement Operator


The bitwise complement operator is a unary operator (works on only one
operand). It is denoted by ~ that changes binary digits 1 to 0 and 0 to 1.

Bitwise Complement
It is important to note that the bitwise complement of any integer N is equal
to -(N + 1). For example,

Consider an integer 35. As per the rule, the bitwise complement of 35


should be -(35 + 1) = -36. Now, let's see if we get the correct answer or not.

35 = 00100011 (In Binary)

// Using bitwise complement operator


~ 00100011
__________
11011100
In the above example, we get that the bitwise complement of 00100011
(35) is 11011100. Here, if we convert the result into decimal we get 220.

However, it is important to note that we cannot directly convert the result


into decimal and get the desired output. This is because the binary result
11011100 is also equivalent to -36.

To understand this we first need to calculate the binary output of -36. We


use 2's complement to calculate the binary of negative integers.

2's Complement

The 2's complement of a number N gives -N.

In binary arithmetic, 1's complement changes 0 to 1 and 1 to 0.

And, if we add 1 to the result of the 1's complement, we get the 2's
complement of the original number.

For example,

36 = 00100100 (In Binary)

1's Complement = 11011011

2's Complement :
11011011
+ 1
_________
11011100

Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This
value is equivalent to the bitwise complement of 35 that we have calculated
in the previous section.

Hence, we can say that the bitwise complement of 35 = -36.


Example 4: Bitwise Complement
#include <iostream>

int main() {
int num1 = 35;
int num2 = -150;
cout << "~(" << num1 << ") = " << (~num1) << endl;
cout << "~(" << num2 << ") = " << (~num2) << endl;

return 0;
}

Run Code

Output

~(35) = -36
~(-150) = 149

In the above example, we declared two integer variables num1 and num2, and
initialized them with the values of 35 and -150 respectively.

We then computed their bitwise complement with the codes (~num1) and
(~num2) respectively and displayed them on the screen.

The bitwise complement of 35 = - (35 + 1) = -36


i.e. ~35 = -36

The bitwise complement of -150 = - (-150 + 1) = - (-149) = 149


i.e. ~(-150) = 149

This is exactly what we got in the output.

C++ Shift Operators


There are two shift operators in C++ programming:
● Right shift operator >>
● Left shift operator <<

5. C++ Right Shift Operator

The right shift operator shifts all bits towards the right by a certain number
of specified bits. It is denoted by >>.

When we shift any number to the right, the least significant bits are
discarded, while the most significant bits are replaced by zeroes.

One bit Right Shift


As we can see from the image above, we have a 4-bit number. When we
perform a one-bit right shift operation on it, each individual bit is shifted to
the right by 1 bit.

As a result, the right-most bit is discarded, while the left-most bit remains
vacant. This vacancy is replaced by a 0.

6. C++ Left Shift Operator


The left shift operator shifts all bits towards the left by a certain number of
specified bits. It is denoted by <<.

One bit Left Shift


As we can see from the image above, we have a 4-bit number. When we
perform a 1 bit left shift operation on it, each individual bit is shifted to the
left by 1 bit.

As a result, the left-most bit is discarded, while the right-most bit remains
vacant. This vacancy is replaced by a 0.

Example 5: Shift Operators


#include <iostream>

int main() {

// declaring two integer variables


int num = 212, i;

// Shift Right Operation


cout << "Shift Right:" << endl;

// Using for loop for shifting num right from 0 bit to 3 bits
for (i = 0; i < 4; i++) {
cout << "212 >> " << i << " = " << (212 >> i) << endl;
}

// Shift Left Operation


cout << "\nShift Left:" << endl;
// Using for loop for shifting num left from 0 bit to 3 bits
for (i = 0; i < 4; i++) {
cout << "212 << " << i << " = " << (212 << i) << endl;
}

return 0;
}

Run Code

Output

Shift Right:
212 >> 0 = 212
212 >> 1 = 106
212 >> 2 = 53
212 >> 3 = 26

Shift Left:
212 << 0 = 212
212 << 1 = 424
212 << 2 = 848
212 << 3 = 1696

From the output of the program above, we can infer that, for any number N,
the results of the shift right operator are:

N >> 0 = N
N >> 1 = (N >> 0) / 2
N >> 2 = (N >> 1) / 2
N >> 3 = (N >> 2) / 2

and so on.

Similarly, the results of the shift left operator are:

N << 0 = N
N << 1 = (N << 0) * 2
N << 2 = (N << 1) * 2
N << 3 = (N << 2) * 2

and so on.
Hence we can conclude that,

N >> m = [ N >> (m-1) ] / 2


N << m = [ N << (m-1) ] * 2

3) Explain logical operators with example.


Ans:
In C++, and logical operators compare two or more operands and return
either true or false values.

We use these operators in decision making.

C++ Logical Operators


We use logical operators to check whether an expression is true or false. If
the expression is true, it returns 1 whereas if the expression is false, it
returns 0.

Oper Example Meaning


ator

&& expression1 && Logical AND.


expression 2

true
only if all the operands are true.

|| expression1 || Logical OR.


expression 2
true if
at least one of the operands is true.

! !expression Logical NOT.

true
only if the operand is false.

C++ Logical AND Operator

The logical AND operator && returns

● true - if and only if all the operands are true.


● false - if one or more operands are false.

Truth Table of && Operator

Let a and b be two operands. 0 represents false while 1 represents true.


Then,

a b a && b

0 0 0

0 1 0

1 0 0
1 1 1

As we can see from the truth table above, the && operator returns true only
if both a and b are true.

Note: The Logical AND operator && should not be confused with the Bitwise
AND operator &.

Example 1: C++ OR Operator


// C++ program demonstrating && operator truth table

#include <iostream>
using namespace std;

int main() {
int a = 5;
int b = 9;

// false && false = false


cout << ((a == 0) && (a > b)) << endl;

// false && true = false


cout << ((a == 0) && (a < b)) << endl;

// true && false = false


cout << ((a == 5) && (a > b)) << endl;

// true && true = true


cout << ((a == 5) && (a < b)) << endl;

return 0;
}

Run Code

Output
0
0
0
1

In this program, we declare and initialize two int variables a and b with the
values 5 and 9 respectively. We then print a logical expression

((a == 0) && (a > b))

Here, a == 0 evaluates to false as the value of a is 5. a > b is also false


since the value of a is less than that of b. We then use the AND operator &&
to combine these two expressions.

From the truth table of && operator, we know that false && false (i.e. 0 &&

0) results in an evaluation of false (0). This is the result we get in the


output.

Similarly, we evaluate three other expressions that fully demonstrate the


truth table of the && operator.

C++ Logical OR Operator

The logical OR operator || returns

● true - if one or more of the operands are true.


● false - if and only if all the operands are false.

Truth Table of || Operator

Let a and b be two operands. Then,


a b a || b

0 0 0

0 1 1

1 0 1

1 1 1

As we can see from the truth table above, the || operator returns false only
if both a and b are false.

Example 2: C++ OR Operator


// C++ program demonstrating || operator truth table

#include <iostream>
using namespace std;

int main() {
int a = 5;
int b = 9;

// false && false = false


cout << ((a == 0) || (a > b)) << endl;

// false && true = true


cout << ((a == 0) || (a < b)) << endl;

// true && false = true


cout << ((a == 5) || (a > b)) << endl;

// true && true = true


cout << ((a == 5) || (a < b)) << endl;

return 0;
}

Run Code

Output

0
1
1
1

In this program, we declare and initialize two int variables a and b with the
values 5 and 9 respectively. We then print a logical expression

((a == 0) || (a > b))

Here, a == 0 evaluates to false as the value of a is 5. a > b is also false


since the value of a is less than that of b. We then use the OR operator ||
to combine these two expressions.

From the truth table of || operator, we know that false || false (i.e. 0 ||

0) results in an evaluation of false (0). This is the result we get in the


output.

Similarly, we evaluate three other expressions that fully demonstrate the


truth table of || operator.

C++ Logical NOT Operator !

The logical NOT operator ! is a unary operator i.e. it takes only one
operand.

It returns true when the operand is false, and false when the operand is
true.
Truth Table of the ! Operator

Let a be an operand. Then,

Example 3: C++ ! Operator


// C++ program demonstrating ! operator truth table
#include <iostream>
using namespace std;

int main() {
int a = 5;

// !false = true
cout << !(a == 0) << endl;

// !true = false
cout << !(a == 5) << endl;

return 0;
}

Run Code

Output

1
0

In this program, we declare and initialize an int variable a with the value 5.
We then print a logical expression

!(a == 0)

Here, a == 0 evaluates to false as the value of a is 5. However, we use the


NOT operator ! on a == 0. Since a == 0 evaluates to false, the ! operator
inverts the results of a == 0 and the final result is true.
Similarly, the expression !(a == 5) ultimately returns false because a == 5

is true.

4) Explain the three looping structures in C++ with examples.


Ans:

Using Loops

In Loop, the statement needs to be written only once and the loop will be
executed 10 times as shown below. In computer programming, a loop is a
sequence of instructions that is repeated until a certain condition is reached.

S.No. Loop Type and Description

1. while loop – First checks the condition, then executes the body.

for loop – firstly initializes, then, condition check, execute body,


2.
update.

3. do-while loop – firstly, execute the body then condition check

For Loop-
A For loop is a repetition control structure that allows us to write a loop that is
executed a specific number of times. The loop enables us to perform n
number of steps together in one line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}

Explanation of the Syntax:

● Initialization statement: This statement gets executed only once, at


the beginning of the for loop. You can enter a declaration of multiple
variables of one type, such as int x=0, a=1, b=2. These variables are
only valid in the scope of the loop. Variable defined before the loop
with the same name are hidden during execution of the loop.
● Condition: This statement gets evaluated ahead of each execution
of the loop body, and abort the execution if the given condition get
false.
● Iteration execution: This statement gets executed after the loop
body, ahead of the next condition evaluated, unless the for loop is
aborted in the body (by break, goto, return or an exception being
thrown.)

NOTES:

● The initialization and increment statements can perform operations


unrelated to the condition statement, or nothing at all – if you wish to
do. But the good practice is to only perform operations directly
relevant to the loop.
● A variable declared in the initialization statement is visible only inside
the scope of the for loop and will be released out of the loop.
● Don’t forget that the variable which was declared in the initialization
statement can be modified during the loop, as well as the variable
checked in the condition.

Example1:
for(int i = 0; i < n; i++)
{
// BODY
}

Flow Diagram of for loop:

Example1:

​ C++
// C++ program to Demonstrate for
loop

#include <iostream>

using namespace std;

int main()

for (int i = 1; i <= 5; i++) {

cout << "Hello World\n";


}

return 0;

Output
Hello World
Hello World
Hello World
Hello World
Hello World

Time complexity: O(1)


Space complexity: O(1)

While Loop-
While studying for loop we have seen that the number of iterations is known
beforehand, i.e. the number of times the loop body is needed to be executed
is known to us. while loops are used in situations where we do not know the
exact number of iterations of the loop beforehand. The loop execution is
terminated on the basis of the test conditions.
We have already stated that a loop mainly consists of three statements –
initialization expression, test expression, and update expression. The syntax of
the three loops – For, while, and do while mainly differs in the placement of
these three statements.
Syntax:
initialization expression;
while (test_expression)
{
// statements

update_expression;
}

Flow Diagram of while loop:


Example:

​ C++

// C++ program to Demonstrate while


loop

#include <iostream>

using namespace std;

int main()

// initialization expression
int i = 1;

// test expression

while (i < 6) {

cout << "Hello World\n";

// update expression

i++;

}
return 0;

Output
Hello World
Hello World
Hello World
Hello World
Hello World

Time complexity: O(1)


Space complexity: O(1)
It’s explanation is same as that of the for loop.

Do-while loop
In Do-while loops also the loop execution is terminated on the basis of test
conditions. The main difference between a do-while loop and the while loop is
in the do-while loop the condition is tested at the end of the loop body, i.e
do-while loop is exit controlled whereas the other two loops are
entry-controlled loops.
Note: In a do-while loop, the loop body will execute at least once irrespective
of the test condition.
Syntax:
initialization expression;
do
{
// statements

update_expression;
} while (test_expression);
Note: Notice the semi – colon(“;”)in the end of loop.

Flow Diagram of the do-while loop:

Example:
​ C++

// C++ program to Demonstrate do-while


loop

#include <iostream>

using namespace std;

int main()

int i = 2; // Initialization
expression
do {

// loop body

cout << "Hello World\n";

// update expression

i++;

} while (i < 1); // test expression


return 0;

Output
Hello World

Time complexity: O(1)


Space complexity: O(1)
In the above program, the test condition (i<1) evaluates to false. But still, as
the loop is an exit – controlled the loop body will execute once.

5) Explain switch case structure in C++ with examples.


Ans:

C++ switch..case Statement


In this tutorial, we will learn about switch statement and its working in C++
programming with the help of some examples.

The switch statement allows us to execute a block of code among many


alternatives.

The syntax of the switch statement in C++ is:

switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;

case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}

How does the switch statement work?

The expression is evaluated once and compared with the values of each
case label.

● If there is a match, the corresponding code after the matching label is


executed. For example, if the value of the variable is equal to
constant2, the code after case constant2: is executed until the break
statement is encountered.
● If there is no match, the code after default: is executed.

Note: We can do the same thing with the if...else..if ladder. However,
the syntax of the switch statement is cleaner and much easier to read and
write.

Flowchart of switch Statement


Flowchart of
C++ switch...case statement

Example: Create a Calculator using the switch Statement


// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;

switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}

return 0;
}

Run Code

Output 1

Enter an operator (+, -, *, /): +


Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -


Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *


Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /


Enter two numbers:
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

Enter an operator (+, -, *, /): ?


Enter two numbers:
2.3
4.5
Error! The operator is not correct.

In the above program, we are using the switch...case statement to perform


addition, subtraction, multiplication, and division.

6) Explain reference variable in C++ with examples.


Ans:
Reference variable is an alternate name of already existing variable. It cannot be

changed to refer another variable and should be initialized at the time of

declaration and cannot be NULL. The operator ‘&’ is used to declare reference

variable.

The following is the syntax of reference variable.

datatype variable_name; // variable declaration


datatype& refer_var = variable_name; // reference variable

Here,

datatype − The datatype of variable like int, char, float etc.

variable_name − This is the name of variable given by user.

refer_var − The name of reference variable.

The following is an example of reference variable.

Example
Live Demo

#include <iostream>
using namespace std;
int main() {
int a = 8;
int& b = a;
cout << "The variable a : " << a;
cout << "\nThe reference variable r : " << b;
return 0;

Output
The variable a : 8

The reference variable r : 8

In the above program, a variable of integer type is declared and initialized with a

value.

int a = 8;

The variable b is declared which is referring variable a.

int& b = a;
7) Explain the difference between call by reference and call by
value.
Ans:

Difference Between Call by Value and Call by Reference


Parameter Call By Value Call By Reference

Convention of In this case, the parameter’s In this case, the parameter’s


Naming value passes for invoking reference passes for the function
the function. In the case of invocation. Whenever calling a
calling a function, we pass function, rather than passing the
the values of variables variables’ values, we pass its
directly to a function. Thus, address instead (location of
it has its name as Call by variables) to the function. Thus,
Value. it has its name as Call by
Reference.

Effects of It copies the value of a Both the passed parameter and


Changes passed parameter into the the argument refer to a similar
function’s argument. Thus, location. Thus, any changes
any changes that occur in occurring in any argument inside
any argument inside the the function also reflects in the
function have no reflection passed parameter.
on the passed parameter.

Type of The method of Call by Value The method of Call by Reference


Passing passes a copy of the passes the variable itself. Here, it
variable. Here, the values of copies the address of the actual
all the variables copy into variables in the calling function
their corresponding dummy into the dummy variables called
variables, also called functions.
functions.
Memory The memory location The memory location referred to
Location referred to by the actual by the actual arguments and
(Referred) arguments and passed passed parameters of a function
parameters of a function are are the same. Meaning, it creates
different. Meaning, it creates the formal and actual arguments
the formal and actual in the very same memory
arguments in different location.
memory locations.

Language Languages like C++, C#. Only the JAVA language


Supported PHP, Visual Basic NET, etc., supports the Call by Reference
provide support to the Call method in programming.
by Value and use it as their
default method.

Value In the Call by Value method, In the Call by Reference method,


Modification there is no modification in there is a modification in the
the original value. original value.

Internal In the case of Call by Value, In the case of Call by Reference,


Implementatio when we pass the value of when we pass the parameter’s
n the parameter during the location reference/address, it
calling of the function, it copies and assigns them to the
copies them to the function’s function’s local argument. Thus,
actual local argument. both the actual argument and
passed parameters refer to one
similar location.

Method of The values of the variables Defining the pointer variables in


Passing in a Call by Value method a Call by Reference method is a
pass using a straightforward prerequisite for storing the
address of all the variables.
method or a Simple
technique.

Manipulation Using this method, any Using this method, one can
of Variables changes occurring to the directly use the addresses to
dummy variables in any access the actual variables.
called function have no Thus, any user can easily alter or
effect on the actual manipulate the variables’ values
variable’s values in the through the function calls.
calling function. Thus, you
cannot alter or manipulate
the actual variables’ values
using the function calls.

8) Explain how you define a class in C++ with an example.


Ans:

C++ Classes
C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with


its attributes and methods. For example: in real life, a car is an
object. The car has attributes, such as weight and color, and
methods, such as drive and brake.

Attributes and methods are basically variables and functions that


belongs to the class. These are often referred to as "class members".

A class is a user-defined data type that we can use in our program,


and it works as an object constructor, or a "blueprint" for creating
objects.
Create a Class
To create a class, use the class keyword:

Example

Create a class called "MyClass":

class MyClass { // The class

public: // Access specifier

int myNum; // Attribute (int variable)

string myString; // Attribute (string variable)

};

Example explained

● The class keyword is used to create a class called MyClass.


● The public keyword is an access specifier, which specifies that
members (attributes and methods) of the class are accessible from
outside the class. You will learn more about access specifiers later.
● Inside the class, there is an integer variable myNum and a string variable
myString. When variables are declared within a class, they are called
attributes.
● At last, end the class definition with a semicolon ;.

9) Explain the various type of constructors in C++ with


examples.
10) Explain static class members with examples.
Ans:

Static Members of a C++ Class

We can define class members static using static keyword. When we declare a

member of a class as static it means no matter how many objects of the class are

created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to

zero when the first object is created, if no other initialization is present. We can't put

it in the class definition but it can be initialized outside the class as done in the

following example by redeclaring the static variable, using the scope resolution

operator :: to identify which class it belongs to.

Let us try the following example to understand the concept of static data members

Live Demo
#include <iostream>

using namespace std;

class Box {
public:
static int objectCount;

// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;

// Increase every time object is created


objectCount++;
}
double Volume() {
return length * breadth * height;
}

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

// Initialize static member of class Box


int Box::objectCount = 0;

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects.


cout << "Total objects: " << Box::objectCount << endl;

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

Constructor called.
Constructor called.
Total objects: 2

11) What is the purpose of destructor with example.


Ans:
Destructor is an instance member function which is invoked automatically
whenever an object is going to be destroyed. Meaning, a destructor is the last
function that is going to be called before an object is destroyed.
● Destructor is also a special member function like constructor.
Destructor destroys the class objects created by constructor.
● Destructor has the same name as their class name preceded by a
tilde (~) symbol.
● It is not possible to define more than one destructor.
● The destructor is only one way to destroy the object create by
constructor. Hence destructor can-not be overloaded.
● Destructor neither requires any argument nor returns any value.
● It is automatically called when object goes out of scope.
● Destructor release memory space occupied by the objects created
by constructor.
● In destructor, objects are destroyed in the reverse of an object
creation.

The thing is to be noted here, if the object is created by using new or the
constructor uses new to allocate memory which resides in the heap memory or
the free store, the destructor should use delete to free the memory.
Syntax:
Syntax for defining the destructor within the class
~ <class-name>()
{

Syntax for defining the destructor outside the class


<class-name>: : ~ <class-name>()
{

​ C++
// Example:

#include<iostream>

using namespace std;

class Test

public:

Test()
{

cout<<"\n Constructor
executed";

~Test()

cout<<"\n Destructor
executed";

};
main()

Test t;

return 0;

Output
Constructor executed
Destructor executed

12) Explain friend function.


Ans:
Friend Function
Like a friend class, a friend function can be granted special access to private
and protected members of a class in C++. They are the non-member functions
that can access and manipulate the private and protected members of the
class for they are declared as friends.
A friend function can be:
1. A global function
2. A member function of another class

Friend Function in C++

Syntax:
friend return_type function_name (arguments); // for a
global function
or
friend return_type class_name::function_name (arguments);
// for a member function of another class

Friend Function Syntax


13) Explain how do you overload a binary operator with
example.
Ans:

Binary Operator Overloading in C++


This section will discuss the Binary Operator Overloading in the C++ programming
language. An operator which contains two operands to perform a mathematical
operation is called the Binary Operator Overloading. It is a polymorphic compile
technique where a single operator can perform various functionalities by taking two
operands from the programmer or user. There are multiple binary operators like +, -, *,
/, etc., that can directly manipulate or overload the object of a class.

For example, suppose we have two numbers, 5 and 6; and overload the binary (+)
operator. So, the binary (+) operator adds the numbers 5 and 6 and returns 11.
Furthermore, we can also perform subtraction, multiplication, and division operation
to use the binary operator for various calculations.

Syntax of the Binary Operator Overloading

Following is the Binary Operator Overloading syntax in the C++ Programming


language.

1. return_type :: operator binary_operator_symbol (arg)


2. {
3. // function definition
4. }
Here,

return_type: It defines the return type of the function.

operator: It is a keyword of the function overloading.

binary_operator_symbol: It represents the binary operator symbol that overloads a


function to perform the calculation.

arg: It defines the argument passed to the function.

Steps to Overload the Binary Operator to Get the Sum of Two


Complex Numbers

Step 1: Start the program.

Step 2: Declare the class.

Step 3: Declare the variables and their member function.

Step 4: Take two numbers using the user-defined inp()function.

Step 6: Similarly, define the binary (-) operator to subtract two numbers.

Step 7: Call the print() function to display the entered numbers.

Step 8: Declare the class objects x1, y1, sum, and sub.

Step 9: Now call the print() function using the x1 and y1 objects.

Step 10: After that, get the object sum and sub result by adding and subtracting the
objects using the '+' and '-' operators.

Step 11: Finally, call the print() and print2() function using the x1, y1, sum, and sub.

Step 12: Display the addition and subtraction of the complex numbers.

Step 13: Stop or terminate the program.

ADVERTISING

Example 1: Program to perform the addition and subtraction of two complex


numbers using the binary (+) and (-) operator
Let's create a program to calculate the addition and subtraction of two complex
numbers by overloading the '+' and '-' binary operators in the C++ programming
language.

Input:
/* use binary (+) operator to add two complex numbers. */

#include <iostream>

using namespace std;

class Complex_num

// declare data member or variables

int x, y;

public:

// create a member function to take input

void inp()

cout << " Input two complex number: " << endl;

cin >> x >> y;

// use binary '+' operator to overload

Complex_num operator + (Complex_num obj)

// create an object
Complex_num A;

// assign values to object

A.x = x + obj.x;

A.y = y + obj.y;

return (A);

// overload the binary (-) operator

Complex_num operator - (Complex_num obj)

// create an object

Complex_num A;

// assign values to object

A.x = x - obj.x;

A.y = y - obj.y;

return (A);

// display the result of addition

void print()

cout << x << " + " << y << "i" << "\n";
}

// display the result of subtraction

void print2()

cout << x << " - " << y << "i" << "\n";

};

int main ()

Complex_num x1, y1, sum, sub; // here we created object of class Addition i.e x1 and
y1

// accepting the values

x1.inp();

y1.inp();

// add the objects

sum = x1 + y1;

sub = x1 - y1; // subtract the complex number

// display user entered values

cout << "\n Entered values are: \n";

cout << " \t";


x1.print();

cout << " \t";

y1.print();

cout << "\n The addition of two complex (real and imaginary) numbers: ";

sum.print(); // call print function to display the result of addition

cout << "\n The subtraction of two complex (real and imaginary) numbers: ";

sub.print2(); // call print2 function to display the result of subtraction

return 0;

Output:
Input two complex numbers:

Input two complex numbers:

Entered values are:

5 + 7i

3 + 5i

The addition of two complex (real and imaginary) numbers: 8 + 12i

The subtraction of two complex (real and imaginary) numbers: 2 - 2i


In the above program, we take two numbers from the user, and then use the binary
operator to overload the '+' and '-' operators to add and subtract two complex
numbers in a class.

14) Explain how you overload a unary operator with example.


Ans:
The unary operators operate on a single operand and following are the examples of

Unary operators −

​ The increment (++) and decrement (--) operators.

​ The unary minus (-) operator.

​ The logical not (!) operator.

The unary operators operate on the object for which they were called and normally,

this operator appears on the left side of the object, as in !obj, -obj, and ++obj but

sometime they can be used as postfix as well like obj++ or obj--.

Following example explain how minus (-) operator can be overloaded for prefix as

well as postfix usage.

Live Demo
#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};

int main() {
Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation


D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

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

F: -11 I:-10
F: 5 I:-11

15) Explain clearly the difference between method overloading


and method overriding.
Ans:
Difference between Function Overloading and Function
Overriding
The following are the important differences between function overloading and

overriding in C++.

S.N
Function Overloading Function Overriding
o.

The concept through which we can The concept through which we

define two or more functions with define a function in parent class

1. the same name and different and the child class with the same

numbers and parameters is known return type and parameters is

as function overloading. known as function overriding.

It can take place without It can take place only when a class
2.
inheritance. inherited from another class.

3. It happens during compile time. It happens during run time.

It is also known as compile time It is also known as run time


4.
polymorphism. polymorphism.

The function overloading can take Function overriding can take place
5.
place multiple times. in the derived class only at once.

Here, the scope of the overloaded Here, the scope of the overridden
6.
functions remain the same. function is different.
No keyword is used during function When the function is defined, it is

7. overloading. preceded by 'virtual' keyword in

main class.

The functions would be redefined The same function is redefined in

8. with the same name, different derived class using 'out' keyword

number or type of parameters

9. Destructor can't be overloaded. Destructor can be overridden.

It can be used to achieve early Overriding is also known as late


10.
binding. binding.

16) Explain the various ways in which a class can be inherited


and their implications.
Ans:
The capability of a class to derive properties and characteristics from another
class is called Inheritance. Inheritance is one of the most important features of
Object-Oriented Programming.
Inheritance is a feature or a process in which, new classes are created from
the existing classes. The new class created is called “derived class” or “child
class” and the existing class is known as the “base class” or “parent class”.
The derived class now is said to be inherited from the base class.
When we say derived class inherits the base class, it means, the derived class
inherits all the properties of the base class, without changing the properties of
base class and may add new features to its own. These new features in the
derived class will not affect the base class. The derived class is the
specialized class for the base class.
● Sub Class: The class that inherits properties from another class is
called Subclass or Derived Class.
● Super Class: The class whose properties are inherited by a subclass
is called Base Class or Superclass.

The article is divided into the following subtopics:


● Why and when to use inheritance?
● Modes of Inheritance
● Types of Inheritance

Why and when to use inheritance?

Consider a group of vehicles. You need to create classes for Bus, Car, and
Truck. The methods fuelAmount(), capacity(), applyBrakes() will be the same
for all three classes. If we create these classes avoiding inheritance then we
have to write all of these functions in each of the three classes as shown
below figure:

You can clearly see that the above process results in duplication of the same
code 3 times. This increases the chances of error and data redundancy. To
avoid this type of situation, inheritance is used. If we create a class Vehicle
and write these three functions in it and inherit the rest of the classes from the
vehicle class, then we can simply avoid the duplication of data and increase
re-usability. Look at the below diagram in which the three classes are inherited
from vehicle class:
Using inheritance, we have to write the functions only one time instead of
three times as we have inherited the rest of the three classes from the base
class (Vehicle).
Implementing inheritance in C++: For creating a sub-class that is inherited
from the base class we have to follow the below syntax.
Derived Classes: A Derived class is defined as the class derived from the
base class.
Syntax:
class <derived_class_name> : <access-specifier>
<base_class_name>
{
//body
}

Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base
class
access-specifier — either of private, public or protected. If neither is specified,
PRIVATE is taken as default
base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data members.
However, it does inherit a full parent object, which contains any private
members which that class declares.
Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }

17) Explain the various kind of inheritance allowed in C++.


Ans:

Types Of Inheritance:-

1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

Types of Inheritance in C++

1. Single Inheritance: In single inheritance, a class is allowed to inherit from


only one class. i.e. one subclass is inherited by one base class only.

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class


can inherit from more than one class. i.e one subclass is inherited from more
than one base class.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created
from another derived class.

4. Hierarchical Inheritance: In this type of inheritance, more than one


subclass is inherited from a single base class. i.e. more than one derived class
is created from a single base class.
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by
combining more than one type of inheritance. For example: Combining
Hierarchical inheritance and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritances:

​ CPP

6. A special case of hybrid inheritance: Multipath inheritance:


A derived class with two base classes and these two base classes have one
common base class is called multipath inheritance. Ambiguity can arise in this
type of inheritance.
18) Explain the need of virtual functions with example
Ans:
Virtual Function in C++
​ Difficulty Level : Medium
​ Last Updated : 10 Jan, 2023

Read

Discuss(20+)

Courses

Practice

Video

A virtual function is a member function which is declared within a base class


and is re-defined (overridden) by a derived class. When you refer to a derived
class object using a pointer or a reference to the base class, you can call a
virtual function for that object and execute the derived class’s version of the
function.

● Virtual functions ensure that the correct function is called for an


object, regardless of the type of reference (or pointer) used for
function call.
● They are mainly used to achieve Runtime polymorphism
● Functions are declared with a virtual keyword in base class.
● The resolving of function call is done at runtime.

Rules for Virtual Functions

1. Virtual functions cannot be static.


2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference of
base class type to achieve runtime polymorphism.
4. The prototype of virtual functions should be the same in the base as
well as derived class.
5. They are always defined in the base class and overridden in a
derived class. It is not mandatory for the derived class to override (or
re-define the virtual function), in that case, the base class version of
the function is used.
6. A class may have virtual destructor but it cannot have a virtual
constructor.

Compile time (early binding) VS runtime (late binding) behavior of Virtual


Functions

Consider the following simple program showing runtime behavior of virtual


functions.

​ CPP
// CPP program to illustrate

// concept of Virtual Functions

#include<iostream>

using namespace std;

class base {

public:
virtual void print()

cout << "print base class\n";

void show()

cout << "show base class\n";

}
};

class derived : public base {

public:

void print()

cout << "print derived class\n";

}
void show()

cout << "show derived class\n";

};

int main()

base *bptr;
derived d;

bptr = &d;

// Virtual function, binded at runtime

bptr->print();

// Non-virtual function, binded at compile


time

bptr->show();
return 0;

Output:

print derived class


show base class

19) What are pure virtual functions, why their required with
example.
Ans:
A pure virtual function in c++ is a virtual function for which we do not
have an implementation. We do not write any functionality in it.
Instead, we only declare this function. A pure virtual function does
not carry any definition related to its base class. A pure virtual
function is declared by assigning a zero (0) in its declaration. Any
class containing one or more pure virtual functions can not be used
to define any object. For this reason, these classes are known as
abstract classes. Classes derived from abstract classes need to
implement the pure virtual functions of these classes.

Syntax
The syntax of the pure virtual function is as follows:

virtual <function_type> <function_name>() = 0;

We need to write "virtual" to create a virtual function. After that, we


declare the type of function, and then the function's name is written.
Since it is a pure virtual function, we must end this function by
assigning the value '0' zero to the function.

Characteristics of Pure Virtual Function in C++


The following are the characteristics of a pure virtual function in
c++:

● A pure virtual function does not do anything, which means it is


used to resemble the template, and the derived classes
implement the function.
● It is an empty function because it does not contain any
definition of the functionality of its base class in it.
● Derived class can call a member or pure virtual function in
c++.
● The user in the derived class redefines a pure virtual function.
● Any class in c++ that contains a pure virtual function does not
allow the user to create the object of that class.

Examples
Let us see an example to understand how to implement a pure
virtual function in c++:

#include <iostream>
using namespace std;
// here is Abstract class
class Shape
{
public:
virtual float cal_Area() = 0; // cal_Area is a pure virtual
function
};
class Square : public Shape
{
float a;
public:
Square(float l)
{
a = l;
}
float cal_Area()
{
return a*a; // returns area of square
}
};
class Circle : public Shape
{
float r;
public:

Circle(float x)
{
r = x;
}
float cal_Area()
{
return 3.14*r*r ;
}
};
class Rectangle : public Shape
{
float l;
float b;
public:
Rectangle(float x, float y)
{
l=x;
b=y;
}
float cal_Area()
{
return l*b; // returns the product of length and breadth
}
};
int main() // main function
{

Shape *shape;
Square s(3.4);
Rectangle r(5,6);
Circle c(7.8);
shape =&s;
int a1 =shape->cal_Area();
shape = &r;
int a2 = shape->cal_Area();
shape = &c;
int a3 = shape->cal_Area();
std::cout << "The area of square is: " <<a1<< std::endl;
std::cout << "The area of rectangle is: " <<a2<< std::endl;
std::cout << "The area of circle is: " <<a3<< std::endl;
return 0;
}

Output:

The area of square is: 11


The area of rectangle is: 30
The area of circle is: 191

20) Explain five manipulators in C++.


Ans:
1. dec

C++ manipulator dec function is used to set the basefield format flag for the str
stream.

When we set basefield to dec, then integer values inserted into the stream are
expressed in decimal base (i.e. radix 10). For input stream, when this flag is set, then
extracted values are also expected to be expressed in decimal base.

Syntax
1. ios_base& dec (ios_base& str);

Parameter

str: stream object whose format flag is affected.

Return value

It returns argument str.

Data Races

Data races may cause when modifies str concurrent access to the same stream
object.

Exceptions
str is in a valid state, if an exception is thrown.

2. endl

C++ manipulator endl function is used to insert a new line character and flush the
stream.

Working of endl manipulator is similar to '\n' character in C++. It prints the output of
the following statement in the next line.

Syntax
1. for ostream
2. ostream& endl (ostream& os);
3.
4. basic template
5. template <class charT, class traits>
6. basic_ostream<charT,traits>& endl (basic_ostream<charT,traits>& os);

Parameter

os: Output stream object affected.

Return value

It returns argument os.

Data Races

Modifies the stream object os.

If we try to concurrent access to the same stream object, then it may cause data
races, except for the standard stream objects cerr, cout, wcout, clog, wcerr and wclog
when these are synchronized with stdio.

Exception Safety

Object os is in a valid state, if any exception is thrown.


3. endl

C++ manipulator ends function is used to insert a null terminating character on os.
The ends manipulator does not take any argument whenever it is invoked. It causes a
null character to the output.

It is similar to '\0' or charT() in C++.

Syntax
1. for ostream
2. ostream& ends (ostream& os);
3.
4. basic template
5. template <class charT, class traits>
6. basic_ostream<charT,traits>& ends (basic_ostream<charT,traits>& os);

Parameter

os: Output stream object where character is inserted.

Return value

It returns argument os.

Data Races

Modifies the stream object os.

If we try to concurrent access to the same stream object then it may cause data
races, except for the standard stream objects cerr, cout, wcout, clog, wcerr and wclog
when these are synchronized with stdio.

Exceptions

Object os is in a valid state, if any exception is thrown.


4. flush

C++ manipulator flush is used to synchronize the associated stream buffer with its
controlled output sequence.

For the stream buffer, objects that implement intermediate buffers, flush function is
used to request all characters written to the controlled sequence.

Syntax
1. for ostream
2. ostream& flush (ostream& os);
3.
4. basic template
5. template <class charT, class traits>
6. basic_ostream<charT,traits>& flush (basic_ostream<charT,traits>& os);

Parameter

os: Output stream object affected.

Return value

It returns argument os.

Data Races

Modifies the stream object os.

If we try to concurrent access to the same stream object then it may cause data
races, except for the standard stream objects cerr, cout, wcout, clog, wcerr and wclog
when these are synchronized with stdio.

Exceptions

Object os is in a valid state, if any exception is thrown.

C++ manipulator hex function is used to set the basefield format flag for the str
stream.
5. hex

When we set basefield to hex, then integer values inserted into the stream are
expressed in hexadecimal base (i.e. radix 16). For input streams, when this flag is set,
then extracted values are also expected to be expressed in hexadecimal base.

Syntax
1. ios_base& hex (ios_base& str);

Parameter

str: stream object whose format flag is affected.

Return value

It returns argument str.

Data Races

Data races may cause when modifies str concurrent access to the same stream
object.

Exceptions

str is in a valid state, if an exception is thrown.

21) Explain how the file can be opened for reading or writing
with example.
Ans:
Opening files in C++

To read or enter data to a file, we need to open it first. This can be performed with the
help of ‘ifstream’ for reading and ‘fstream’ or ‘ofstream’ for writing or appending to the
file. All these three objects have open() function pre-built in them.
Syntax:

1 open( FileName , Mode );

Here:

FileName – It denotes the name of file which has to be opened.

Mode – There different mode to open a file and it explained in this article.

Mode Description

iso::in File opened in reading mode

iso::out File opened in write mode

iso::app File opened in append mode

iso::ate File opened in append mode but read and write performed
at the end of the file.

File opened in binary mode


iso::binary

File opened in truncate mode


iso::trunc

The file opens only if it exists


iso::nocreate

The file opens only if it doesn’t exist


iso::noreplace

In C++, we can use two modes simultaneously with the help of | (OR) operator.
Program for Opening File:

2
#include<iostream>
3
#include<fstream>
4
using namespace std;
5
int main(){
6
fstream FileName;
7
FileName.open("FileName", ios::out);
8
if (!FileName){
9
cout<<"Error while creating the file";
1
0 }

1 else{
1
cout<<"File created successfully";
1
2 FileName.close();

1 }
3
return 0;
1
4 }

1
5

Explanation of above code

1. Here we have an iostream library, which is responsible for input/output


stream.
2. We also have a fstream library, which is responsible for handling files.
3. Creating an object of the fstream class and named it as ‘FileName’.
4. On the above-created object, we have to apply the open() function to
create a new file, and the mode is set to ‘out’ which will allow us to write
into the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Prints the message to console if the file exists/created.
8. We use the close() function on the object to close the file.

Output

File created successfully

Writing to File

Till now, we learned how to create the file using C++. Now, we will learn how to write
data to file which we created before. We will use fstream or ofstream object to write
data into the file and to do so; we will use stream insertion operator (<<) along with
the text enclosed within the double-quotes.

With the help of open() function, we will create a new file named ‘FileName’ and then
we will set the mode to ‘ios::out’ as we have to write the data to file.

Syntax:

1 FileName<<"Insert the text here";

Program for Writing to File:

#include<iostream>
1
#include<fstream>
2
using namespace std;
3
int main() {
4
fstream FileName;
5
FileName.open("FileName.txt", ios::out);
6
if (!FileName) {
7
cout<<" Error while creating the file ";
8
}
9
else {
1
0
cout<<"File created and data got written to file";
1 FileName<<"This is a blog posted on Great Learning";
1
FileName.close();
1
2 }

1 return 0;
3
}
1
4

1
5

1
6

Explanation of above code

1. Here we have an iostream library, which is responsible for input/output


stream.
2. We also have a fstream library, which is responsible for handling files.
3. Creating an object of the fstream class and named it as ‘FileName’.
4. On the above-created object, we have to apply the open() function to
create a new file, and the mode is set to ‘out’ which will allow us to write
into the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Prints the message to console if the file exists/created.
8. Writing the data to the created file.
9. We use the close() function on the object to close the file.

Output

File created and data got written to file

Reading from file in C++

Getting the data from the file is an essential thing to perform because without getting
the data, we cannot perform any task. But don’t worry, C++ provides that option too.
We can perform the reading of data from a file with the CIN to get data from the user,
but then we use CIN to take inputs from the user’s standard console. Here we will
use fstream or ifstream.

Syntax:
1 FileName>>Variable;

Content of FileName.txt:

Hello World, Thank You for Visiting Great Learning.

Program for Reading from File:

1 #include<iostream>

2 #include <fstream>

3 using namespace std;

4 int main() {

5 fstream FileName;

6 FileName.open("FileName.txt", ios::in);

7 if (!FileName) {

8 cout<<"File doesn’t exist.";

9 }

1 else {
0
char x;
1
1 while (1) {

1 FileName>>x;
2
if(FileName.eof())
1
break;
3
cout<<x;
1
4 }
1 }
5
FileName.close();
1
6 return 0;
1 }
7

1
8

1
9

2
0

2
1

Explanation of above code

1. Here we have an iostream library, which is responsible for input/output


stream.
2. We also have a fstream library which is responsible for handling files.
3. Creating an object of the fstream class and named it ‘FileName’.
4. On the above-created object, we have to apply the open() function to
create a new file, and the mode is set to ‘in’ which will allow us to read
from the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Creating a character(char) variable with the named x.
8. Iterating of the file with the help of while loop.
9. Getting the file data to the variable x.
10. Here we are using if condition with eof() which stands for the end of the file
to tell the compiler to read till the file’s end.
11. We use the ‘break’ statement to stop the reading from file when it reaches
the end.
12. The print statement to print the content that is available in the variable x.
13. We use the close() function on the object to close the file

Output

Hello World, Thank You for Visiting Great Learning.


22) Explain how you create a template function with example.
Ans:
Function Templates:

We can define a template for a function. For example, if we have an add() function,
we can create versions of the add function for adding the int, float or double type
values.

Function Template

○ Generic functions use the concept of a function template. Generic functions


define a set of operations that can be applied to the various types of data.

○ The type of the data that the function will operate on depends on the type of
the data passed as a parameter.

○ For example, Quick sorting algorithm is implemented using a generic function,


it can be implemented to an array of integers or array of floats.

○ A Generic function is created by using the keyword template. The template


defines what function will do.

Syntax of Function Template


template < class Ttype> ret_type func_name(parameter_list)

// body of function.

Where Ttype: It is a placeholder name for a data type used by the function. It is used
within the function definition. It is only a placeholder that the compiler will
automatically replace this placeholder with the actual data type.

class: A class keyword is used to specify a generic type in a template declaration.

Let's see a simple example of a function template:


#include <iostream>

using namespace std;

template<class T> T add(T &a,T &b)

T result = a+b;

return result;

int main()

int i =2;

int j =3;

float m = 2.3;

float n = 1.2;

cout<<"Addition of i and j is :"<<add(i,j);

cout<<'\n';

cout<<"Addition of m and n is :"<<add(m,n);

return 0;

Output:
Addition of i and j is :5

Addition of m and n is :3.5

In the above example, we create the function template which can perform the
addition operation on any type either it can be integer, float or double.

23) Explain the exception handling mechanism in C++ with


example.
Ans:
One of the advantages of C++ over C is Exception Handling. Exceptions are
runtime anomalies or abnormal conditions that a program encounters during
its execution. There are two types of exceptions: a)Synchronous,
b)Asynchronous (i.e., exceptions which are beyond the program’s control,
such as disc failure, keyboard interrupts etc.). C++ provides the following
specialized keywords for this purpose:
try: Represents a block of code that can throw an exception.
catch: Represents a block of code that is executed when a particular exception
is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a
function throws but doesn’t handle itself.
Why Exception Handling?
The following are the main advantages of exception handling over traditional
error handling:
1) Separation of Error Handling code from Normal Code: In traditional error
handling codes, there are always if-else conditions to handle errors. These
conditions and the code to handle errors get mixed up with the normal flow.
This makes the code less readable and maintainable. With try/catch blocks,
the code for error handling becomes separate from the normal flow.
2) Functions/Methods can handle only the exceptions they choose: A function
can throw many exceptions, but may choose to handle some of them. The
other exceptions, which are thrown but not caught, can be handled by the
caller. If the caller chooses not to catch them, then the exceptions are handled
by the caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw
keyword. The caller of this function must handle the exception in some way
(either by specifying it again or catching it).
3) Grouping of Error Types: In C++, both basic types and objects can be
thrown as exceptions. We can create a hierarchy of exception objects, group
exceptions in namespaces or classes and categorize them according to their
types.

C++ Exceptions:
When executing C++ code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message.
The technical term for this is: C++ will throw an exception (error).
C++ try and catch:
Exception handling in C++ consists of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
The throw keyword throws an exception when a problem is detected, which
lets us create a custom error.
The catch statement allows you to define a block of code to be executed if an
error occurs in the try block.
The try and catch keywords come in pairs:
We use the try block to test some code: If the value of a variable “age” is less
than 18, we will throw an exception, and handle it in our catch block.
In the catch block, we catch the error if it occurs and do something about it.
The catch statement takes a single parameter. So, if the value of age is 15 and
that’s why we are throwing an exception of type int in the try block (age), we
can pass “int myNum” as the parameter to the catch statement, where the
variable “myNum” is used to output the value of age.
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater
than 18), the catch block is skipped.
Exception Handling in C++
1) The following is a simple example to show exception handling in C++. The
output of the program explains the flow of execution of try/catch blocks.

​ CPP
#include <iostream>

using namespace std;

int main()

int x = -1;

// Some code

cout << "Before try \n";


try {

cout << "Inside try \n";

if (x < 0)

throw x;

cout << "After throw (Never executed)


\n";

catch (int x ) {
cout << "Exception Caught \n";

cout << "After catch (Will be executed) \n";

return 0;

Output:
Before try
Inside try
Exception Caught
After catch (Will be executed)

2) There is a special catch block called the ‘catch all’ block, written as
catch(…), that can be used to catch all types of exceptions. For example, in
the following program, an int is thrown as an exception, but there is no catch
block for int, so the catch(…) block will be executed.
3) Implicit type conversion doesn’t happen for primitive types. For example, in
the following program, ‘a’ is not implicitly converted to int.
4) If an exception is thrown and not caught anywhere, the program terminates
abnormally. For example, in the following program, a char is thrown, but there
is no catch block to catch the char.
5) A derived class exception should be caught before a base class exception.
See this for more details.
6) Like Java, the C++ library has a standard exception class which is the base
class for all standard exceptions. All objects thrown by the components of the
standard library are derived from this class. Therefore, all standard exceptions
can be caught by catching this type
7) Unlike Java, in C++, all exceptions are unchecked, i.e., the compiler doesn’t
check whether an exception is caught or not (See this for details). So, it is not
necessary to specify all uncaught exceptions in a function declaration.
Although it’s a recommended practice to do so. For example, the following
program compiles fine, but ideally the signature of fun() should list the
unchecked exceptions.
8) In C++, try/catch blocks can be nested. Also, an exception can be re-thrown
using “throw; “.
A function can also re-throw a function using the same “throw; ” syntax. A
function can handle a part and ask the caller to handle the remaining.
9) When an exception is thrown, all objects created inside the enclosing try
block are destroyed before the control is transferred to the catch block.
10) You may like to try Quiz on Exception Handling in C++.

24) Explain how dynamic polymorphism is implemented in C++


with example.
Ans:

● Dynamic Polymorphism

Dynamic Polymorphism implies the runtime resolution of

function call. It is implies via Overriding which in turn is followed

by inheritance in c++.
Here are the examples showing the implementation of static as well

as dynamic polymorphism.

Dynamic polymorphism in C++


Dynamic polymorphism is not so simple as it appears in the syntax.

Compiler has to resolve the overloaded function call at runtime. Our

aim is to perform this resolution of correct function call efficiently.

Incase of a simple non casted pointer for an object , we can use this

approach and it is also known as early binding as the call is

bound to the object pointer at compile time.

But incase of casting , early binding would not help. During

upcasting, if we need to invoke the polymorphed function then we

have to implement the base function as a virtual function. Virtual

functions ensure that the correct function is called for an object,

regardless of the type of reference (or pointer) used for function call.

This is also called late binding.


Dynamic polymorphism with virtual functions

This is a general way of implementing dynamic polymorphism in

C++. Compiler will resolve the call to polymorphed function using

virtual table.
25) Explain the various file modes in C++.
Ans:

File Modes

In C++, for every file operation, exists a specific file mode. These file modes allow us to
create, read, write, append or modify a file. The file modes are defined in the class ios.
Let's see all these different modes in which we could open a file on disk.

File Modes Description


ios::in
Searches for the file and opens it in the read mode only(if the file
is found).

ios::out
Searches for the file and opens it in the write mode. If the file is
found, its content is overwritten. If the file is not found, a new
file is created. Allows you to write to the file.

ios::app
Searches for the file and opens it in the append mode i.e. this
mode allows you to append new data to the end of a file. If the
file is not found, a new file is created.

"ios::binary"
Searches for the file and opens the file(if the file is found) in a
binary mode to perform binary input/output file operations.

ios::ate
Searches for the file, opens it and positions the pointer at the
end of the file. This mode when used with ios::binary, ios::in and
ios::out modes, allows you to modify the content of a file.

"ios::trunc"
Searches for the file and opens it to truncate or deletes all of its
content(if the file is found.

"ios::nocreate"
Searches for the file and if the file is not found, a new file will not
be created.
26) Explain five arithmetic operators in C++ with examples.
Ans:
C++ has 5 basic arithmetic operators. They are −

​ Addition(+)

​ Subtraction(-)

​ Division(/)

​ Multiplication(*)

​ Modulo(%)

Addition Operator

Addition Arithmetic Operators are used to add 2 values and


variables in a program statement. The symbol used for this type of
operator is ‘+’. In simple words, Addition combines 2 numbers.

Subtraction Operator

Subtraction Arithmetic Operator is used to subtract 2 values or


variables in the program. The symbol used for this operator is ‘-’.

Multiplication Operator

This operator is denoted by the ‘*’ or ‘x’ symbol. It gives the


product of two numbers.

Division Operator

This Arithmetic Operator divides its first operand by the second


operand. It is denoted by the ‘/’ symbol. In C++, if we divide An
Integer with another Integer then we will get the Quotient as the
result. But if either of the operands is a floating-point number, then
the result of division will be in Decimals.

Modulus Operator

This type of Arithmetic Operator computes the remainder of the two


values when divided. The symbol used to define this operator is
‘%’. Both the operands must be integer type only. If they are of the
floating-point type, then there might arise a compile-time error.

These operators can operate on any arithmetic operations in C++. Let's have a

look at an example −

Example
#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl ;

c = a - b;
cout << "Line 2 - Value of c is :" << c << endl ;

c = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl ;

c = a % b;
cout << "Line 5 - Value of c is :" << c << endl ;
return 0;
}

Output
This will give the output −

Line 1 - Value of c is :31


Line 2 - Value of c is :11
Line 3 - Value of c is :210
Line 4 - Value of c is :2
Line 5 - Value of c is :1

27) Explain how you create a pointer to an integer variable and


use to access/modify the variable.
Ans:
Pointers are symbolic representations of addresses. They enable
programs to simulate call-by-reference as well as to create and
manipulate dynamic data structures. Iterating over elements in arrays or
other data structures is one of the main use of pointers.
The address of the variable you’re working with is assigned to the
pointer variable that points to the same data type (such as an int or
string).
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int
data
How to use a pointer?
● Define a pointer variable
● Assigning the address of a variable to a pointer using the unary
operator (&) which returns the address of that variable.
● Accessing the value stored in the address using unary operator
(*) which returns the value of the variable located at the address
specified by its operand.

The reason we associate data type with a pointer is that it knows how
many bytes the data is stored in. When we increment a pointer, we
increase the pointer by the size of the data type to which it points.
​ C++
// C++ program to illustrate Pointers

#include <bits/stdc++.h>

using namespace std;

void geeks()

int var = 20;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be


same

ptr = &var;

// assign the address of a variable to a pointer

cout << "Value at ptr = " << ptr << "\n";

cout << "Value at var = " << var << "\n";

cout << "Value at *ptr = " << *ptr << "\n";


}

// Driver program

int main()

geeks();

return 0;

Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20
28) Explain how you create a pointer to an object and use to
access the members of the class.
Ans:

Create a class along with data member and member functions and then
access the member functions by using a pointer in C++.

How to access a member function by pointer?


To access a member function by pointer, we have to declare a pointer to the
object and initialize it (by creating the memory at runtime, yes! We can use
new keyboard for this).

The second step, use arrow operator -> to access the member function using
the pointer to the object.

C++ syntax to access member function by pointer


//pointer to object declaration
class_name *pointe_name;
//memory initialization at runtime
pointer_name = new class_name;
//accessing member function by using arrow operator
pointer_name->member_function();

Example:

In the below example - there is a class named Number with private data
member num and public member functions inputNumber(),
displayNumber().

In the example, we are creating simple object N and a pointer to the object
ptrN and accessing the member functions by using simple object N and the
pointer to the object ptrN.

C++ program to access member function by pointer


#include <iostream>
using namespace std;

class Number {
private:
int num;

public:
//constructor
Number() { num = 0; };

//member function to get input


void inputNumber(void)
{
cout << "Enter an integer number: ";
cin >> num;
}
//member function to display number
void displayNumber()
{
cout << "Num: " << num << endl;
}
};

//Main function
int main()
{
//declaring object to the class number
Number N;
//input and display number using norn object
N.inputNumber();
N.displayNumber();

//declaring pointer to the object


Number* ptrN;
ptrN = new Number; //creating & assigning memory

//printing default value


cout << "Default value... " << endl;
//calling member function with pointer
ptrN->displayNumber();

//input values and print


ptrN->inputNumber();
ptrN->displayNumber();

return 0;
}

Output
Enter an integer number: 10
Num: 10
Default value...
Num: 0
Enter an integer number: 20
Num: 20

Explanation:

The main three steps needs to be understood those are:

1. Pointer to object creation: Number *ptrN;


2. Dynamic memory initialization to the pointer object: ptrN = new
Number;
3. Accessing member function by using "Arrow Operator":
ptrN->displayNumber();

29) Explain how you open a file in C++ and read its contents.
Ans:

Read a File in C++


Say we have a shopping list stored in a .txt file:

eggs
ham
eggs and spam
spam and eggs

Our goal is to print the list’s contents to the console. Before we start writing our
program, let’s include the relevant header files:

#include <iostream>
#include <fstream>
#include <string>

We’re now ready to write our function. Let’s first declare our fstream variable and
connect it to a stream object by opening the file:

int main () {
std::ifstream myfile; myfile.open("shopping_list.txt");
Strictly speaking, we could have performed that action in a single line, using the
class constructor to open the file directly when initializing the stream object:

int main () {
std::ifstream myfile ("shopping_list.txt"); // this is
equivalent to the above method

Before we get to read the file’s contents into our stream, all that’s left to do is to
declare a string variable that can hold the contents:

std::string mystring;

Read a File in C++ Using the >> Operator


For starters, let’s use the stream input operator >> to read in our list from the file.

if ( myfile.is_open() ) { // always check whether the file is


open
myfile >> mystring; // pipe file's content into stream
std::cout << mystring; // pipe stream's content to standard
output
}

Note that the ifstream destructor closes our file automatically, which is one of the
perks of using this class. If we wanted, we could have added an infile.close()
command to the end of the program. This is seen as good practice, but it does not
really add any value.
When we run that function, here’s the output we get on the screen:

eggs

That’s not what we expected. Our function printed only the first item of our shopping
list. That’s because the >> operator reads a string only until it encounters a white
space character (such as a space or line break). To read the entire file, we can place
the line into a while loop:

if ( myfile.is_open() ) { while ( myfile.good() ) {


myfile >> mystring;
std::cout << mystring;
} }
Once we reach the end of the file, myfile.good() evaluates to False, causing the while
loop to terminate. We can abbreviate the condition as follows:

while ( myfile ) {

This is equivalent to asking if our file is good. How does our code perform now?

eggshameggsandspamspamandeggseggs

Two things happened here: All our shopping items got chained together, with the last
item being printed twice. While the latter has to do with how C++ handles buffered
data and is out of the scope of this tutorial, the first was to be expected. After all, >>
ignores whitespace, meaning that all the space and newline characters get lost. How
can we include that information in the output? The answer to that question lies in the
get() function.

Read a File in C++ Using get()


We’ll replace >> with get(), a member function of our fstream class that reads in one
character at a time. The great thing about get() is that it does not ignore white space
and instead treats it as a series of ordinary characters. To read in the file’s contents
in their entirety, we’ll stick to our while-loop:

if ( myfile.is_open() ) {
char mychar;
while ( myfile ) {
mychar = myfile.get();
std::cout << mychar;
}
}

How does the output of our little script look now?

eggs
ham
eggs and spam
spam and eggs

Success! Our entire shopping list was printed to the console. To demonstrate that
this function really does stream each character one by one, let’s add a little
functionality that tells us the position of the stream’s pointer after each output.

std::cout << ": " << myfile.tellg() << ", " ;


The tellg() function’s name is short for “tell get.” It returns the current position of the
pointer as it moves through the input stream. Once the entire file has been traversed,
tellg() returns the value -1.
Let’s look at just the first two lines of the output after running the modified code:

e: 2, g: 3, g: 4, s: 5,
: 6, h: 7, a: 8, m: 9,

For every get() action, the standard output shows the letter of the input, and the
position of the pointer. We can see that every character was indeed processed
individually, causing the code to evaluate the pointer’s position after every single
character, be it a letter or white space.

Read a File in C++ Using getline()


For our use case, there’s little point in processing every character separately — after
all, we want to print every line from our shopping list to the screen one by one. This
calls for getline(), another member function, which reads in the text until it encounters
a line break. Here’s how we would modify our code:

std::string myline;
if ( myfile.is_open() ) {
while ( myfile ) {
std::getline (myfile, myline);
std::cout << myline << ": " << myfile.tellg() << '\n';
}
}

And here’s the output:

eggs: 5
ham: 9
eggs and spam: 23
spam and eggs: 37

The pointer’s position is now evaluated after every line read in by our file stream.
To wrap things up, here’s the final version of our script for reading a file in C++ line
by line:

#include <iostream>
#include <fstream>
#include <string>
int main (){
std::ifstream myfile;
myfile.open("shopping_list.txt");
std::string myline;
if ( myfile.is_open() ) {
while ( myfile ) { // equivalent to myfile.good()
std::getline (myfile, myline);
std::cout << myline << '\n';
}
}
else {
std::cout << "Couldn't open file\n";
}
return 0; }

Adding an else-condition, as we did at the end of this script, is a good idea if you
encounter a problematic file. Instead of simply terminating wordlessly, the script will
tell you that it was not able to open the file.

You might also like