C++ Question Set
1. What is C++?
Ans
C++ is a
general purpose programming language and widely used now a days for competitive
programming. It has imperative, object-oriented and generic programming
features. C++ runs on lots of platform like Windows, Linux, Unix, Mac etc.
2. Why learn C++? (features)
Ans
1) C++ is used to develop games, desktop apps, operating systems, browsers, and so on because of its performance.
2) After learning C++, it will be much easier to learn other programming languages like Java, Python, etc.
3) C++ helps you to understand the internal architecture of a computer, how computer stores and retrieves information.
3. What is object-oriented programming?
Ans
Object-Oriented Programming or OOPs refers to
languages that uses objects in programming. Object-oriented programming aims to
implement real-world entities like inheritance, hiding, polymorphism etc in
programming. The main aim of OOP is to bind together the data and the functions
that operate on them so that no other part of the code can access this data
except that function.
4. Advantage
of OOPs over Procedure-oriented programming language.
Ans
1) OOPs makes
development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows.
2) OOPs provide data hiding whereas in Procedure-oriented programming language a global data can be accessed from anywhere.
3) OOPs provide ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.
5. What is
diff between C/C++? / Diff between procedural programming language and object
oriented programming language?
Ans
|
Sr.
No. |
Key |
C |
C++ |
|
1 |
Introduction |
C was
developed by Dennis Ritchie in around 1969 at AT&T Bell Labs. |
C++ was
developed by Bjarne Stroustrup in 1979. |
|
2 |
Language Type |
As mentioned before C is procedural programming. |
On the other hand, C++ supports both procedural and object-oriented programming paradigms. |
|
3 |
OOPs feature Support |
As C does not support the OOPs concept so it has no support for polymorphism, encapsulation, and inheritance. |
C++ has support for polymorphism, encapsulation, and inheritance as it is being an object-oriented programming language |
|
4 |
Data Security |
As C
does not support encapsulation so data behave as a free entity and can be
manipulated by outside code. |
On
another hand in the case of C++ encapsulation hides the data to ensure that
data structures and operators are used as intended. |
|
5 |
Driven
type |
C in
general known as function-driven language. |
On the
other hand, C++ is known as object driven language. |
|
6 |
Feature
supported |
C does
not support function and operator overloading also do not have namespace
feature and reference variable functionality. |
On the
other hand, C++ supports both function and operator overloading also have
namespace feature and reference variable functionality. |
6. More datatypes in C++ : 1. String 2. Boolean
3. References.
Ans
1) String
The string type is used to store a sequence of characters (text).
This is not a built-in type, but it behaves like one in its most basic usage.
String values must be surrounded by double quotes:
Example
string greeting = "Hello";
cout << greeting;
To use strings, you must include an additional header file in
the source code, the <string> library:
Example
// Include the string library
#include <string>
// Create a string variable
string greeting = "Hello";
// Output string value
cout << greeting;
2) Boolean
A boolean data type is declared with the bool keyword and can
only take the values true or false. When the value is returned, true = 1 and
false = 0.
Example
#include <iostream>
using namespace std;
int main() {
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun;
// Outputs 1 (true)
cout << isFishTasty;
// Outputs 0 (false)
return 0;
}
Output
1
0
3) References
A reference variable is a "reference" to an
existing variable, and it is created with the & operator:
string food = "Pizza"; // food variable
string &meal = food;
// reference to food
Now, we can use either the variable name food or the
reference name meal to refer to the food variable:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
return 0;
}
Output
Pizza
Pizza
7. Call by
value and call by reference.
Ans
1) Call by value in C++
In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().
Example
1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }
Value of the data is: 3
Here, address of the value is passed in the function, so actual and formal arguments share the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.
Example
1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }
Output:
8. OOPs
concepts in C++?
Ans
1) Class
2) Object
3) Inheritance
4) Polymorphism
5) Abstraction
6) Encapsulation
9. What are
classes and objects?
Ans
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 in
C++ is the building block, that leads to Object-Oriented programming. It is a
user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A C++
class is like a blueprint for an object.
An Object
is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
10. How to use
classes and objects?
Ans
Syntax :
class className{
Access specifier: // private, protected or public
Data members; // variables to be used
Member functions; // methods of the class
} ;
Declaring Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName;
Accessing Data Members
The public data members are also accessed in the same way given however the private data members are not allowed to be accessed directly by the object. Accessing a data member depends solely on the access control of that data member.
11. Ways to
define methods (functions) of a class.
Ans
There are 2 ways to define a member function:
1) Inside class definition
class hello
{
public:
void printData1()
{
printf("This is from inside class defination.\n");
}
};
2) Outside class definition
class hello{public:void printData();};void hello::printData(){printf("This is from outside class defination\n");
}
12. What is
inline function?
Ans
Inline
function is one of the important feature of C++. So, let’s first understand why
inline functions are used and what is the purpose of inline function?
When the
program executes the function call instruction the CPU stores the memory
address of the instruction following the function call, copies the arguments of
the function on the stack and finally transfers control to the specified
function. The CPU then executes the function code, stores the function return
value in a predefined memory location/register and returns control to the
calling function. This can become overhead if the execution time of function is
less than the switching time from the caller function to called function
(callee). For functions that are large and/or perform complex tasks, the
overhead of the function call is usually insignificant compared to the amount
of time the function takes to run. However, for small, commonly-used functions,
the time needed to make the function call is often a lot more than the time
needed to actually execute the function’s code. This overhead occurs for small
functions because execution time of small function is less than the switching
time.
C++
provides an inline functions to reduce the function call overhead. Inline
function is a function that is expanded in line when it is called. When the
inline function is called whole code of the inline function gets inserted or
substituted at the point of inline function call. This substitution is
performed by the C++ compiler at compile time. Inline function may increase
efficiency if it is small.
The syntax
for defining the function inline:
inline return-type function-name(parameters)
{
// function code
}
Remember,
inlining is only a request to the compiler, not a command. Compiler can ignore
the request for inlining. Compiler may not perform inlining in such
circumstances like:
1) If a
function contains a loop. (for, while, do-while)
2) If a
function contains static variables.
3) If a
function is recursive.
4) If a
function return type is other than void, and the return statement doesn’t exist
in function body.
5) If a
function contains switch or goto statement.
13. What is
static data members and functions?
Ans
v Static data members
Static data
members are class members that are declared using static keywords. A static
member has certain special characteristics. These are:
· It is visible only within the class, but its lifetime is the entire program
#include <iostream>using namespace std;
class hello{public:static int a;void printStatic();};void hello::printStatic(){printf("Static member's value : %d \n", a);a++;}int hello::a = 10;int main(){hello h1, h2;h.printStatic();h2.printStatic();return 0;}
OutputStatic member's value : 10Static member's value : 11
v Static member functions
A static member function can only access static data member, other static member functions and any other functions from outside the class.
14. What is friend function and friend classes?
Ans
v Friend Function
a) A member of another classTo make function of other class friend :
class className {... .. ...friend returnType className :: functionName(arguments);... .. ...}
b) A global functionTo make a global function friend :
class className {... .. ...friend returnType functionName(arguments);... .. ...}
v Friend Class
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
Since ClassB is a friend class, we can access all members of ClassA from inside ClassB.
15. What is
constructor?
Ans
A
constructor is a special type of member function of a class which initializes
objects of a class. Constructor is automatically called when an object (instance
of class) is created. It is special member function of the class because it
does not have any return type.
Constructor
has same name as the class itself.
It must be
placed in public section of class.
Syntax :
class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};
16. Types of
constructor?
Ans
There are
three types of constructor:
1) Default
constructor
2) Parameterized
constructor
3) Copy
constructor
·
Default constructor
Default constructor is the constructor which doesn’t take any
argument. It has no parameters. Even if we do not define any constructor
explicitly, the compiler will automatically provide a default constructor
implicitly.
·
Parameterized constructor
It is possible to pass arguments to constructors. Typically,
these arguments help initialize an object when it is created. To create a
parameterized constructor, simply add parameters to it the way you would to any
other function. When you define the constructor’s body, use the parameters to
initialize the object.
·
Copy constructor
A copy constructor is a member function which initializes an
object using another object of the same class.
17. What is
this pointer?
Ans
The this
pointer holds the address of current object, in simple words you can say that
this pointer points to the current object of the class.
Example of this pointer :
Here you can see that we have two data members num and ch. In member function setMyValues() we have two local variables having same name as data members name. In such case if you want to assign the local variable value to the data members then you won’t be able to do until unless you use this pointer, because the compiler won’t know that you are referring to object’s data members unless you use this pointer. This is one of the example where you must use this pointer.
#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
void setMyValues(int num, char ch){
this->num =num;
this->ch=ch;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
obj.setMyValues(100, 'A');
obj.displayMyValues();
return 0;
}
Output:
100
A
18. What is
constructor overloading?
à
In C++, We
can have more than one constructor in a class with same name, as long as each
has a different list of arguments. This concept is known as Constructor
Overloading and is quite similar to function overloading.
·
Overloaded constructors essentially have the same name
(exact name of the class) and differ by number and type of arguments.
·
A constructor is called depending upon the number and
type of arguments passed.
·
While creating the object, arguments must be passed to
let compiler know, which constructor needs to be called.
19. What is
destructor?
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.
Destructors
have same name as the class preceded by a tilde (~)
Destructors
don’t take any argument and don’t return anything
Properties
of Destructor:
·
Destructor function is automatically invoked when the
objects are destroyed.
·
The destructor does not have arguments.
·
It has no return type not even void.
·
A destructor should be declared in the public section
of the class.
20. What are
access specifiers?
Ans
Access
Modifiers or Access Specifiers in a class are used to assign the accessibility
to the class members. That is, it sets some restrictions on the class members
not to get directly accessed by the outside functions.
There are 3
types of access modifiers available in C++:
1) public - members
are accessible from outside the class
2) private -
members cannot be accessed (or viewed) from outside the class
3) protected -
members cannot be accessed from outside the class, however, they can be
accessed in inherited classes. You will learn more about Inheritance later.
Note: If we
do not specify any access modifiers for the members inside the class then by
default the access modifier for the members will be Private.
It is
possible to access private members of a class using a public method inside the
same class.
21. What is use
of scope resolution operator?
Ans
1) It is used
to access the hidden variables or member functions of a program.
2) It defines
the member function outside of the class using the scope resolution.
3) It is used
to access the static variable and static function of a class.
4) The scope
resolution operator is used to override function in the Inheritance.
22.What is
encapsulation?
Ans
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public method inside class as these methods have access of private data of class..
Example :
#include <iostream>
using namespace std;
class Employee {
private:
// Private
attribute
int salary;
public:
// Setter
void setSalary(int
s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout <<
myObj.getSalary();
return 0;
}
23. What is
inheritance?
Ans
The
capability of a class to derive properties and characteristics from another
class is called Inheritance. Inheritance is one of the most important feature
of Object Oriented Programming.
Inheritance
is one of the key features of Object-oriented programming in C++. It allows us
to create a new class (derived class) from an existing class (base class).
The derived
class inherits the features (data members and functions) from the base class
and can have additional features of its own.
The idea of
inheritance implements the is a relationship. For example, mammal IS-A animal,
dog IS-A mammal hence dog IS-A animal as well and so on.
Base and
Derived Classes :
A class can
be derived from more than one classes, which means it can inherit data and
functions from multiple base classes. To define a derived class, we use a class
derivation list to specify the base class(es). A class derivation list names
one or more base classes and has the form −
class
derived-class : access-specifier base-class
Where
access-specifier is one of public, protected, or private, and base-class is the
name of a previously defined class. If the access-specifier is not used, then
it is private by default.
Access
Control and Inheritance :
A derived
class can access all the non-private members of its base class. Thus base-class
members that should not be accessible to the member functions of derived
classes should be declared private in the base class.
We can
summarize the different access types according to - who can access them in the
following way −
|
Access |
public |
protected |
private |
|
Same
class |
yes |
yes |
yes |
|
Derived
classes |
yes |
yes |
no |
|
Outside
classes |
yes |
no |
no |
A derived
class inherits all base class methods with the following exceptions −
·
Constructors, destructors and copy constructors of the
base class.
·
Overloaded operators of the base class.
·
The friend functions of the base class.
24. Advantage
of C++ Inheritance
Ans
Code
reusability: Now you can reuse the members of your parent class. So, there is
no need to define the member again. So less code is required in the class.
25. Types of inheritance?
Ans
C++ supports five types of inheritance:
·
Single inheritance
·
Multilevel inheritance
·
Multiple inheritance
·
Hierarchical inheritance
·
Hybrid inheritance
1) Single
Inheritance
Single inheritance is defined as the inheritance in which a derived
class is inherited from the only one base class.
When one class inherits another class, it is known as single
level inheritance.
Where 'A' is the base class, and 'B' is the derived class.
2) Multilevel
Inheritance
Multilevel inheritance is a process of deriving a class from
another derived class.
When one class inherits another class which is further
inherited by another class, it is known as multi level inheritance in C++.
Inheritance is transitive so the last derived class acquires all the members of
all its base classes.
3) Multiple
Inheritance
Multiple inheritance is the process of deriving a new class
that inherits the attributes from two or more classes.
4) Hybrid
Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
5) Hierarchical
Inheritance
Hierarchical inheritance is defined as the process of
deriving more than one class from a base class.
26. Constructor
in derived class?
Ans
Constructors
are called from „top” to „bottom”: first from the base class, then from the
derived class. If a class inherits from several classes, their constructors are
invoked in the order they are mentioned in the inheritance list in the
definition of the derived class.
·
We can use constructors in derived classes in C++
·
If the base class constructor does not have any
arguments, there is no need for any constructor in the derived class
·
But if there are one or more arguments in the base
class constructor, derived class need to pass argument to the base class constructor
·
If both base and derived classes have constructors,
base class constructor is executed first
27. What is
polymorphism?
Ans
The word
polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
A real-life example of polymorphism, a person at the same time can have
different characteristics. Like a man at the same time is a father, a husband,
an employee. So the same person posses different behavior in different situations.
This is called polymorphism. Polymorphism is considered as one of the important
features of Object Oriented Programming.
Types of
Polymorphism in Oops
·
Static Binding (or Compile time) Polymorphism, e.g.,
Method Overloading
·
Dynamic Binding (or Runtime) Polymorphism, e.g.,
Method overriding
28. Differences
b/w compile time and run time polymorphism.
Ans
|
Compile
time polymorphism |
Run time polymorphism |
|
The function to be invoked is known at the compile
time. |
The function to be invoked is known at the run
time. |
|
It is also known as overloading, early binding and
static binding. |
It is also known as overriding, Dynamic binding and
late binding. |
|
Overloading is a compile time polymorphism where
more than one method is having the same name but with the different number of
parameters or the type of the parameters. |
Overriding is a run time polymorphism where more
than one method is having the same name, number of parameters and the type of
the parameters. |
|
It is achieved by function overloading and operator
overloading. |
It is achieved by virtual functions and pointers. |
|
It provides fast execution as it is known at the
compile time. |
It provides slow execution as it is known at the
run time. |
|
It is less flexible as mainly all the things
execute at the compile time. |
It is more flexible as all the things execute at
the run time. |
29. What is
function overloading?
Ans
Function
overloading is simply a feature in C++ where more than one function can share
the same name but have different arguments /parameters.
And,
depending upon the number/type of arguments, different functions are called.
It's a
compile-time polymorphism because the compiler knows which function to execute
before the program is compiled.
Example
// C++ program to overload sum() function
#include <iostream>
using namespace
std;
// Function with 2 int parameters
int sum(int
num1, int
num2)
{
return
num1 + num2;
}
// Function with 2 double parameters
double sum(double
num1, double
num2)
{
return
num1 + num2;
}
// Function with 3 int parameters
int sum(int
num1, int
num2, int
num3)
{
return
num1 + num2
+ num3;
}
int main()
{
// Call function with 2 int
parameters
cout
<< "Sum
1 = " <<
sum(5,
6) <<
endl;
// Call function with 2 double
parameters
cout
<< "Sum
2 = " <<
sum(5.5,
6.6) <<
endl;
// Call function with 3 int
parameters
cout
<< "Sum
3 = " <<
sum(5,
6, 7)
<< endl;
return
0;
}
Output
Sum 1 =
11
Sum 2 =
12.1
Sum 3 =
18
30. What is
operator overloading?
Ans
In C++, we
can overload an operator as long as we are operating on user-defined types like
objects or structures.
We cannot
use operator overloading for basic types such as int, double, etc.
Operator
overloading is basically function overloading, where different operator
functions have the same symbol but different operands.
And,
depending on the operands, different operator functions are executed.
This is
also a compile-time polymorphism.
Example
// C++ program to overload ++ when used as prefix
#include <iostream>
using namespace
std;
class Count
{
private:
int
value;
public:
// Constructor to initialize count to 5
Count()
: value(5)
{}
// Overload ++ when used as prefix
void
operator++()
{
value
= value + 1;
}
void
display()
{
cout
<< "Count:
" <<
value <<
endl;
}
};
int main()
{
Count
count1;
// Call the "void operator ++()" function
++count1;
count1.display();
return
0;
}
Output
Count: 6
31. What is
function overriding?
Ans
Function
overriding in C++ is a feature that allows us to use a function in the child
class that is already present in its parent class. The child class inherits all the data
members, and the member functions present in the parent class. If you wish to
override any functionality in the child class, then you can implement function
overriding. Function overriding means creating a newer version of the parent
class function in the child class.
It's a
runtime polymorphism because the function call is not resolved by the compiler,
but it is resolved in the runtime instead.
Example
// C++ program to demonstrate function overriding
#include <iostream>
using namespace
std;
class Base
{
public:
virtual
void print()
{
cout
<< "Base
Function" <<
endl;
}
};
class Derived
: public Base
{
public:
void
print()
{
cout
<< "Derived
Function" <<
endl;
}
};
int main()
{
Derived
derived1;
// Call print() function of Derived class
derived1.print();
return
0;
}
Output
Derived
Function
32. Diff
between function overloading and function overriding?
Ans
1) Inheritance:
Overriding of functions occurs when one class is inherited from another class.
Overloading can occur without inheritance.
2) Function
Signature: Overloaded functions must differ in function signature ie
either number of parameters or type of parameters should differ. In overriding,
function signatures must be same.
3) Scope of
functions: Overridden functions are in different scopes; whereas
overloaded functions are in same scope.
4) Behavior of
functions: Overriding is needed when derived class function has to do
some added or different job than the base class function. Overloading is used
to have same name functions which behave differently depending upon parameters
passed to them.
33. What is
virtual function?
· It is used to tell the compiler to perform dynamic linkage or late binding on the function.
· There is a necessity to use the single pointer to refer to all the objects of the different classes. So, we create the pointer to the base class that refers to all the derived objects. But, when base class pointer contains the address of the derived class object, always executes the base class function. This issue can only be resolved by using the 'virtual' function.
· A 'virtual' is a keyword preceding the normal declaration of a function.
·
Virtual functions must be members of some class.
·
Virtual functions cannot be static members.
·
They are accessed through object pointers.
·
They can be a friend of another class.
·
A virtual function must be defined in the base class,
even though it is not used.
·
The prototypes of a virtual function of the base class
and all the derived classes must be identical. If the two functions with the
same name but different prototypes, C++ will consider them as the overloaded
functions.
·
We cannot have a virtual constructor, but we can have
a virtual destructor
Example
#include <iostream>
using namespace
std;
class A
{
public:
virtual
void display()
{
cout
<< "Base
class is invoked" <<
endl;
}
};
class B
: public A
{
public:
void
display()
{
cout
<< "Derived
Class is invoked" <<
endl;
}
};
int main()
{
A *a;
// pointer of base class
B b;
// object of derived class
a = &b;
a->display();
// Late Binding occurs
}
Output
Derived
Class is invoked
34. What is
virtual base class?
Ans
The virtual
base class is used when a derived class has multiple copies of the base class.
Virtual
base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using
multiple inheritances.
Need for
Virtual Base Classes:
Consider
the situation where we have one class A .This class is A is inherited by two
other classes B and C. Both these class are inherited into another in a new
class D.
35. What is
pure virtual function and abstract class?
Ans
· When the function has no definition, such function is known as "do-nothing" function.
· The "do-nothing" function is known as a pure virtual function. A pure virtual function is a function declared in the base class that has no definition relative to the base class.
· A class containing the pure virtual function cannot be used to declare the objects of its own, such classes are known as abstract base classes.
36. What is
exception handling?
Ans
An exception is a problem
that arises during the execution of a program. A C++ exception is a response to
an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to
transfer control from one part of a program to another. C++ exception handling
is built upon three keywords: try, catch, and throw.
·
throw −
A program throws an exception when a problem shows up. This is done using
a throw keyword.
·
catch −
A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword
indicates the catching of an exception.
·
try −
A try block identifies a block of code for which particular
exceptions will be activated. It's followed by one or more catch blocks.
Assuming a block will raise
an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block
is referred to as protected code, and the syntax for using try/catch as follows
–
try {
//
protected code
} catch( ExceptionName e1 ) {
// catch
block
} catch( ExceptionName e2 ) {
// catch
block
} catch( ExceptionName eN ) {
// catch
block
}
You can list down multiple catch statements
to catch different type of exceptions in case your try block raises
more than one exception in different situations.
Throwing Exceptions
Exceptions can be thrown
anywhere within a code block using throw statement. The operand of the
throw statement determines a type for the exception and can be any expression
and the type of the result of the expression determines the type of exception
thrown.
Following is an example of
throwing an exception when dividing by zero condition occurs –
double division(int a, int b) {
if( b == 0
) {
throw
"Division by zero condition!";
}
return
(a/b);
}
Catching Exceptions
The catch block
following the try block catches any exception. You can specify what
type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.
try {
//
protected code
} catch( ExceptionName e ) {
// code to
handle ExceptionName exception
}
Above code will catch an exception
of ExceptionName type. If you want to specify that a catch block
should handle any type of exception that is thrown in a try block, you must put
an ellipsis, ..., between the parentheses enclosing the exception declaration
as follows –
try {
//
protected code
} catch(...) {
// code to
handle any exception
}
The following is an example,
which throws a division by zero exception and we catch it in catch block.
#include <iostream>
using namespace std;
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Because we are raising an
exception of type const char*, so while catching this exception, we have
to use const char* in catch block. If we compile and run above code, this would
produce the following result −
Division by zero condition!
37. What is
file handling?
Ans
Files store
data permanently in a storage device. With file handling, the output from a program
can be stored in a file. Various operations can be performed on the data while
in the file.
The term
“Data” is commonly referred to as known facts or information. In the present
era, data plays a vital role. It helps to describe, diagnose, predict or
prescribe. But to achieve all this, we need to store it somewhere. You all
would argue that there are so many text editors like ‘Notepad’ and ‘MS Office’,
which help us store data in the form of text. You are right! But here we are
discussing at a level of programming. In contrast, text editors like ‘Notepad’
and ‘MS Office’ are pre-built and cannot be accessed at the programming level
to store data. File Handling is a hot topic when it comes to storing such
programming data.
Almost
every programming language has a ‘File Handling’ method to deal with the
storage of data.
file
handling is further divided into sub-topics:
·
Create a file
·
Open a file
·
Read from a file
·
Write to a file
·
Close a file
fstream
library
Before
diving into each sub-topics, let us first learn about the header file we will
be using to gain access to the file handling method. In C++, fstream library is
used to handle files, and it is dealt with the help of three classes known as
ofstream, ifstream and fstream.
ofstream:
This class
helps create and write the data to the file obtained from the program’s output.
It is also known as the input stream.
ifstream:
We use this
class to read data from files and also known as the input stream.
fstream:
This class
is the combination of both ofstream and ifstream. It provides the capability of
creating, writing and reading a file.
To access
the following classes, you must include the fstream as a header file like how
we declare iostream in the header.
Example:
#include<iostream>
#include<fstream>
After
including the header file, there comes a question saying do we need to create
the file within the program or else do we need to use an existing file. But
this isn’t that difficult to answer because, in C++, we get four different methods
to handle files. Let’s discuss them one by one.
File
Operations in C++
C++
provides us with four different operations for file handling. They are:
1) open() –
This is used to create a file.
2) read() – This is used to read the data from the
file.
3) write() –
This is used to write new data to file.
4) close() –
This is used to close the file.
1) 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:
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. |
|
iso::binary |
File opened in
binary mode |
|
iso::trunc |
File opened in
truncate mode |
|
iso::nocreate |
The file opens
only if it exists |
|
iso::noreplace |
The file opens
only if it doesn’t exist |
In C++, we
can use two modes simultaneously with the help of | (OR) operator.
Program for
Opening File:
#include<iostream>
#include<fstream>
using
namespace std;
int main(){
fstream FileName;
FileName.open("FileName",
ios::out);
if (!FileName){
cout<<"Error while creating
the file";
}
else{
cout<<"File created
successfully";
FileName.close();
}
return 0;
}
Explanation
of above code
I.
Here we have an iostream library, which is responsible
for input/output stream.
II.
We also have a fstream library, which is responsible
for handling files.
III.
Creating an object of the fstream class and named it
as ‘FileName’.
IV.
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.
V.
We use the ‘if’ statement to check for the file
creation.
VI.
Prints the message to console if the file doesn’t
exist.
VII.
Prints the message to console if the file exists/created.
VIII.
We use the close() function on the object to close the
file.
Output
File
created successfully
2) 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:
FileName<<"Insert
the text here";
Program for
Writing to File:
#include<iostream>
#include<fstream>
using
namespace std;
int main()
{
fstream FileName;
FileName.open("FileName.txt",
ios::out);
if (!FileName) {
cout<<" Error while creating
the file ";
}
else {
cout<<"File created and data
got written to file";
FileName<<"This is a blog
posted on Great Learning";
FileName.close();
}
return 0;
}
Explanation
of above code
I.
Here we have an iostream library, which is responsible
for input/output stream.
II.
We also have a fstream library, which is responsible
for handling files.
III.
Creating an object of the fstream class and named it
as ‘FileName’.
IV.
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.
V.
We use the ‘if’ statement to check for the file
creation.
VI.
Prints the message to console if the file doesn’t
exist.
VII.
Prints the message to console if the file
exists/created.
VIII.
Writing the data to the created file.
IX.
We use the close() function on the object to close the
file.
Output
File
created and data got written to file
3) 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:
FileName>>Variable;
Content of
FileName.txt:
Hello
World, Thank You for Visiting Great Learning.
Program for
Reading from File:
#include<iostream>
#include
<fstream>
using
namespace std;
int main()
{
fstream FileName;
FileName.open("FileName.txt",
ios::in);
if (!FileName) {
cout<<"File doesn’t
exist.";
}
else {
char x;
while (1) {
FileName>>x;
if(FileName.eof())
break;
cout<<x;
}
}
FileName.close();
return 0;
}
Explanation
of above code
I.
Here we have an iostream library, which is responsible
for input/output stream.
II.
We also have a fstream library which is responsible
for handling files.
III.
Creating an object of the fstream class and named it
‘FileName’.
IV.
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.
V.
We use the ‘if’ statement to check for the file
creation.
VI.
Prints the message to console if the file doesn’t
exist.
VII.
Creating a character(char) variable with the named x.
VIII.
Iterating of the file with the help of while loop.
IX.
Getting the file data to the variable x.
X.
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.
XI.
We use the ‘break’ statement to stop the reading from
file when it reaches the end.
XII.
The print statement to print the content that is
available in the variable x.
XIII.
We use the close() function on the object to close the
file.
Output
Hello
World, Thank You for Visiting Great Learning.
Comments
Post a Comment