C++ QB Ans
C++ QB Ans
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
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
Qualifier:
Operator Description
| Bitwise OR Operator
Note: Bitwise operators can only be used alongside char and int data
types.
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:
00001100
& 00011001
_________
00001000 = 8 (In decimal)
int main() {
// declare variables
int a = 12, b = 25;
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,
a b a|b
0 0 0
0 1 1
1 0 1
1 1 1
Example 2: Bitwise OR
#include <iostream>
int main() {
int a = 12, b = 25;
return 0;
}
Run Code
Output
a = 12
b = 25
a | b = 29
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:
int main() {
int a = 12, b = 25;
Run Code
Output
a = 12
b = 25
a ^ b = 21
Bitwise Complement
It is important to note that the bitwise complement of any integer N is equal
to -(N + 1). For example,
2's Complement
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,
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.
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 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.
As a result, the right-most bit is discarded, while the left-most bit remains
vacant. This vacancy is replaced by a 0.
As a result, the left-most bit is discarded, while the right-most bit remains
vacant. This vacancy is replaced by a 0.
int main() {
// 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;
}
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.
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,
true
only if all the operands are true.
true
only if the operand is false.
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 &.
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 9;
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
From the truth table of && operator, we know that false && false (i.e. 0 &&
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.
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 9;
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
From the truth table of || operator, we know that false || false (i.e. 0 ||
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
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)
is true.
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.
1. while loop – First checks the condition, then executes the body.
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
}
NOTES:
Example1:
for(int i = 0; i < n; i++)
{
// BODY
}
Example1:
C++
// C++ program to Demonstrate for
loop
#include <iostream>
int main()
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
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;
}
C++
#include <iostream>
int main()
// initialization expression
int i = 1;
// test expression
while (i < 6) {
// update expression
i++;
}
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
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.
Example:
C++
#include <iostream>
int main()
int i = 2; // Initialization
expression
do {
// loop body
// update expression
i++;
Output
Hello World
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
}
The expression is evaluated once and compared with the values of each
case label.
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.
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
Output 2
Output 3
Output 4
Output 5
declaration and cannot be NULL. The operator ‘&’ is used to declare reference
variable.
Here,
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
In the above program, a variable of integer type is declared and initialized with a
value.
int a = 8;
int& b = a;
7) Explain the difference between call by reference and call by
value.
Ans:
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.
C++ Classes
C++ is an object-oriented programming language.
Example
};
Example explained
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
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
Let us try the following example to understand the concept of static data members
Live Demo
#include <iostream>
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;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
return 0;
}
When the above code is compiled and executed, it produces the following result −
Constructor called.
Constructor called.
Total objects: 2
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>()
{
C++
// Example:
#include<iostream>
class Test
public:
Test()
{
cout<<"\n Constructor
executed";
~Test()
cout<<"\n Destructor
executed";
};
main()
Test t;
return 0;
Output
Constructor executed
Destructor executed
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
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.
Step 6: Similarly, define the binary (-) operator to subtract two 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.
ADVERTISING
Input:
/* use binary (+) operator to add two complex numbers. */
#include <iostream>
class Complex_num
int x, y;
public:
void inp()
cout << " Input two complex number: " << endl;
// create an object
Complex_num A;
A.x = x + obj.x;
A.y = y + obj.y;
return (A);
// create an object
Complex_num A;
A.x = x - obj.x;
A.y = y - obj.y;
return (A);
void print()
cout << x << " + " << y << "i" << "\n";
}
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
x1.inp();
y1.inp();
sum = x1 + y1;
y1.print();
cout << "\n The addition of two complex (real and imaginary) numbers: ";
cout << "\n The subtraction of two complex (real and imaginary) numbers: ";
return 0;
Output:
Input two complex numbers:
5 + 7i
3 + 5i
Unary operators −
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
Following example explain how minus (-) operator can be overloaded for prefix as
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;
}
int main() {
Distance D1(11, 10), D2(-5, 11);
return 0;
}
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11
overriding in C++.
S.N
Function Overloading Function Overriding
o.
1. the same name and different and the child class with the same
It can take place without It can take place only when a class
2.
inheritance. inherited from another class.
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
main class.
8. with the same name, different derived class using 'out' keyword
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
{ }
Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
CPP
Read
Discuss(20+)
Courses
Practice
Video
CPP
// CPP program to illustrate
#include<iostream>
class base {
public:
virtual void print()
void show()
}
};
public:
void print()
}
void show()
};
int main()
base *bptr;
derived d;
bptr = &d;
bptr->print();
bptr->show();
return 0;
Output:
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:
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:
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
Return value
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
Return value
Data Races
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
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.
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
Return value
Data Races
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
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
Return value
Data Races
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
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
Return value
Data Races
Data races may cause when modifies str concurrent access to the same stream
object.
Exceptions
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:
Here:
Mode – There different mode to open a file and it explained in this article.
Mode Description
iso::ate File opened in append mode but read and write performed
at the end of the file.
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
Output
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:
#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
Output
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:
1 #include<iostream>
2 #include <fstream>
4 int main() {
5 fstream FileName;
6 FileName.open("FileName.txt", ios::in);
7 if (!FileName) {
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
Output
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
○ The type of the data that the function will operate on depends on the type of
the data passed as a parameter.
// 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.
T result = a+b;
return result;
int main()
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<'\n';
return 0;
Output:
Addition of i and j is :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.
C++ Exceptions:
When executing C++ code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message.
The technical term for this is: C++ will throw an exception (error).
C++ try and catch:
Exception handling in C++ consists of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
The throw keyword throws an exception when a problem is detected, which
lets us create a custom error.
The catch statement allows you to define a block of code to be executed if an
error occurs in the try block.
The try and catch keywords come in pairs:
We use the try block to test some code: If the value of a variable “age” is less
than 18, we will throw an exception, and handle it in our catch block.
In the catch block, we catch the error if it occurs and do something about it.
The catch statement takes a single parameter. So, if the value of age is 15 and
that’s why we are throwing an exception of type int in the try block (age), we
can pass “int myNum” as the parameter to the catch statement, where the
variable “myNum” is used to output the value of age.
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater
than 18), the catch block is skipped.
Exception Handling in C++
1) The following is a simple example to show exception handling in C++. The
output of the program explains the flow of execution of try/catch blocks.
CPP
#include <iostream>
int main()
int x = -1;
// Some code
if (x < 0)
throw x;
catch (int x ) {
cout << "Exception Caught \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++.
● Dynamic Polymorphism
by inheritance in c++.
Here are the examples showing the implementation of static as well
as dynamic polymorphism.
Incase of a simple non casted pointer for an object , we can use this
regardless of the type of reference (or pointer) used for function call.
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.
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
Subtraction Operator
Multiplication Operator
Division Operator
Modulus Operator
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 −
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>
void geeks()
ptr = &var;
// 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++.
The second step, use arrow operator -> to access the member function using
the pointer to the object.
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.
class Number {
private:
int num;
public:
//constructor
Number() { num = 0; };
//Main function
int main()
{
//declaring object to the class number
Number N;
//input and display number using norn object
N.inputNumber();
N.displayNumber();
return 0;
}
Output
Enter an integer number: 10
Num: 10
Default value...
Num: 0
Enter an integer number: 20
Num: 20
Explanation:
29) Explain how you open a file in C++ and read its contents.
Ans:
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;
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:
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.
if ( myfile.is_open() ) {
char mychar;
while ( myfile ) {
mychar = myfile.get();
std::cout << mychar;
}
}
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.
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.
std::string myline;
if ( myfile.is_open() ) {
while ( myfile ) {
std::getline (myfile, myline);
std::cout << myline << ": " << myfile.tellg() << '\n';
}
}
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.