0% found this document useful (0 votes)
3 views36 pages

answers c++

The document explains exception handling in C++, detailing the concepts of try, catch, and throw keywords. It also discusses the advantages of using exceptions, the use of catch(...) handlers, and provides examples of arithmetic exception handling, rethrowing exceptions, and multiple catch blocks. Additionally, it covers inheritance, virtual base classes, abstract classes, constructors, and pointers in C++, along with their applications and rules.

Uploaded by

soumyabiradar20
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)
3 views36 pages

answers c++

The document explains exception handling in C++, detailing the concepts of try, catch, and throw keywords. It also discusses the advantages of using exceptions, the use of catch(...) handlers, and provides examples of arithmetic exception handling, rethrowing exceptions, and multiple catch blocks. Additionally, it covers inheritance, virtual base classes, abstract classes, constructors, and pointers in C++, along with their applications and rules.

Uploaded by

soumyabiradar20
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/ 36

4th

1 Define Exception. Explain how exceptions are


handled in C++.
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
}

2 Discuss the advantages of using exception handling


mechanisms in a program
1: Separating Error-Handling Code from "Regular"
Code:- Exceptions provide the means to separate the
details of what to do when something out of the
ordinary happens from the main logic of a program. In
traditional programming, error detection, reporting, and
handling often lead to confusing spaghetti code.
Exceptions enable you to write the main flow of your
code and to deal with the exceptional cases elsewhere.

2: Propagating Errors Up the Call Stack:- A second


advantage of exceptions is the ability to propagate error
reporting up the call stack of methods.

3: Grouping and Differentiating Error


Types:- Because all exceptions thrown within a
program are objects, the grouping or categorizing of
exceptions is a natural outcome of the class hierarchy.

3. Explain when a catch(...) handler is used.

A C++ exception handler is a catch clause. When an


exception is thrown from statements within a try block,
the list of catch clauses that follows the try block is
searched to find a catch clause that can handle the
exception.
A catch clause consists of three parts: the
keyword catch, the declaration of a single type or single
object within parentheses (referred to as an exception
declaration), and a set of statements within a
compound statement. If the catch clause is selected to
handle an exception, the compound statement is
executed

4. Explain try/catch block to handle arithmetic


exceptions.
Exception handling in C++ consist 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:
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18
years old.\n";
cout << "Age is: " << myNum;
}
We use the try block to test some code: If
the age variable is less than 18, we will throw an
exception, and handle it in our catch block.
In the catch block, we catch the error and do something
about it. The catch statement takes a parameter: in our
example we use an int variable (myNum) (because we
are throwing an exception of int type in the try block
(age)), to output the value of age.
If no error occurs (e.g. if age is 20 instead of 15,
meaning it will be be greater than 18), the catch block is
skipped

5. Write a C++ program to demonstrate the concept


of rethrowing an
exception.
#include <iostream>
using namespace std;
int main()
{
try
{
int a, b;
cout<<"Enter two integer values: ";
cin>>a>>b;
try
{
if(b == 0)
{
throw b;
}
else
{
cout<<(a/b);
}
}
catch(...)
{
throw; //rethrowing the exception
}
}
catch(int)
{
cout<<"Second value cannot be zero";
}
return 0;
}

6. Write a C++ program that illustrates the


application of multiple catch
blocks.

#include<iostream.h>
#include<conio.h>
void main()
{
int a=2;

try
{

if(a==1)
throw a; //throwing integer ex
ception
else if(a==2)
throw 'A'; //throwing character
exception

else if(a==3)
throw 4.5; //throwing float exce
ption

}
catch(int a)
{
cout<<"\nInteger exception caught.";
}
catch(char ch)
{
cout<<"\nCharacter exception caught.";
}
catch(double d)
{
cout<<"\nDouble exception caught.";
}

cout<<"\nEnd of program.";
}
Output :

Character exception caught.


End of program.

7. Write a C++ program to perform the following


operations: A function to read two numbers from
keyboard. A function to calculate the division of
these two numbers. A try block to throw an
exception when a wrong type of data is keyed in. A
try block to detect and throw an exception if the
condition “divide-by-zero” occurs. Appropriate
catch blocks to handle the exceptions thrown.
#include <iostream>

using namespace std;

class exe
{
double a,b;
public:
void read()
{
cout<<"\nEnter two double type numbers:";
cin>>a>>b;
}
void div()
{
try{

if(cin.fail())
throw "Bad input!";
if( b == 0 )
throw 0;

cout<<"\nAns is "<<a/b;
}
catch(const int n)
{
cout << "\nDivision by " << n << " not
allowed\n";
}
catch(const char* Str)
{
cout<< Str;
}
}
};
int main()
{
exe ex;
ex.read();
ex.div();
return 0;
}

5th
1. Explain Inheritance. List and explain with neat
diagrams, the different
types of Inheritances in C++ programming.
Inheritance is the capability of one class to acquire
properties and characteristics from another class. The
class whose properties are inherited by other class is
called the Parent or Base or Super class. And, the class
which inherits properties of other class is
called Child or Derived or Sub class.
Inheritance makes the code reusable. When we inherit
an existing class, all its methods and fields become
available in the new class, hence code is reused.
In C++, we have 5 different types of Inheritance.
Namely,
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual
Inheritance)
Single Inheritance in C++
In this type of inheritance one derived class inherits
from only one base class. It is the most simplest form of
Inheritance.
Multiple Inheritance in C++
In this type of inheritance a single derived class may
inherit from two or more than two base classes.

Hierarchical Inheritance in C++


In this type of inheritance, multiple derived classes
inherits from a single base class.
Multilevel Inheritance in C++
In this type of inheritance the derived class inherits
from a class, which in turn inherits from some other
class. The Super class for one, is sub class for the other.

Hybrid (Virtual) Inheritance in C++


Hybrid Inheritance is combination of Hierarchical and
Mutilevel Inheritance.
3 Explain the virtual base class. when do we make a
class virtual. Justify
with the help of program.
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 as shown in figure below.
As we can see from the figure that data
members/function of class A are inherited twice to
class D. One through class B and second through
class C. When any data / function member of class A is
accessed by an object of class D, ambiguity arises as to
which data/function member would be called? One
inherited through B or the other inherited through C.
This confuses compiler and it displays error.
Example: To show the need of Virtual Base Class in
C++

#include <iostream>

using namespace std;

class A {

public:

void show()

cout << "Hello form A \n";

};

class B : public A {

};
class C : public A {

};

class D : public B, public C {

};

int main()

D object;

object.show();

Define abstract classes. Write a C++ program to


demonstrate the use of abstract classes in C++
abstract class in C++ is a class that has at
least one pure virtual function (i.e., a function that has
no definition). The classes inheriting the abstract
class must provide a definition for the pure virtual
function; otherwise, the subclass would become an
abstract class itself.
#include <iostream>
using namespace std;
class A { public:
virtual void test() = 0;
};
class B : public A
{
public: void test()
{ cout << "Hello I am the virtual function running in
derived class!! :)" << endl; } };
int main(void)
{
B obj;
obj.test();
return 0; }
Class D is derived from class B, Class D does not
contain any of its data
members. Does class D require constructors?
Justify.

Yes , class D requires constructor even if it doesn’t


contain any data member of its own. Derived class
constructor is used to provide the values to the base
class constructor.
Example-
#include
Using namespace std;
class alpha
{
int p;
public:
alpha(int i)
{
p=i;
cout<<"alpha initializedn";
}
void show_p(void)
{
cout<<"p="<<p<<"n";
}</p<<"n";>
};
class beta
{
float q;
public:
beta(float j)
{
q=j;
cout<<"beta initializedn";
}
void show_ q(void)
{
cout<<"q="<<q<<"n";
}</q<<"n";>
};
class gamma: public beta , public alpha
{
int x,y;
public:
gamma(int a, float b, int c, int d):
alpha (a),beta(b)
{
x =c;
y =d;
cout<<"gamma initializedn";
}
viod show_xy(void)
{
cout<<"x="<<x<<"n";
cout<<"y="<<y<<"n";
}</y<<"n";></x<<"n";>
};
int main( )
{
gamma g(5,10.75,20,30);
cout<<"n";
g.show_p( );
g.show_q( );
g.show_xy( );
getch( );
}
Write and explain the C++ program to demonstrate
the use of
constructors in: multiple inheritance and multilevel
inheritance

Multilevel Inheritance
In C++ programming, not only you can derive a class
from the base class but you can also derive a class from
the derived class. This form of inheritance is known as
multilevel inheritance.

class A {
... .. ...
};
class B: public A {
... .. ...
};
class C: public B {
... ... ...
};

Here, class B is derived from the base class A and the


class C is derived from the derived class B.
Multilevel Inheritance

#include <iostream>
using namespace std;

class A {
public:
void display() {
cout<<"Base class content.";
}
};

class B : public A {};

class C : public B {};

int main() {
C obj;
obj.display();
return 0;
}
Output
Base class content.
In this program, class C is derived from class B (which
is derived from base class A).
The obj object of class C is defined in
the main() function.
When the display() function is called, display() in
class A is executed. It's because there is
no display() function in class C and class B.
The compiler first looks for the display() function in
class C. Since the function doesn't exist there, it looks
for the function in class B (as C is derived from B).
The function also doesn't exist in class B, so the
compiler looks for it in class A (as B is derived
from A).
If display() function exists in C, the compiler
overrides display() of class A (because of member
function overriding).

Explain nesting of classes in C++. Explain the way of


nesting of two classes (class beta and class gamma)
inside first class (class alpha).
Demonstrate with C++ program.
A nested class is a class which is declared in another
enclosing class. A nested class is a member and as such
has the same access rights as any other member. The
members of an enclosing class have no special access
to members of a nested class; the usual access rules
shall be obeyed.
#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}
Output
Nested classes in C++
The number is 9

th
6
Define Pointer and this Pointer. What does this
pointer point to?
C++ pointers are easy and fun to learn. Some C++ tasks
are performed more easily with pointers, and other C++
tasks, such as dynamic memory allocation, cannot be
performed without them.
As you know every variable is a memory location and
every memory location has its address defined which
can be accessed using ampersand (&) operator which
denotes an address in memory
This pointer:
Every object in C++ has access to its own address
through an important pointer called this pointer.
The this pointer is an implicit parameter to all member
functions. Therefore, inside a member function, this
may be used to refer to the invoking object.
Friend functions do not have a this pointer, because
friends are not members of a class. Only member
functions have a this pointer.

List the applications of this Pointer.


Applications of this pointer
 Return Object. One of the important applications of
using this pointer is to return the object it points. ...
 Method Chaining. After returning the object from a
function, a very useful application would be to chain
the methods for ease and a cleaner code. ...
 Distinguish Data Members.

4. Explain pointers to the derived class.

A derived class is a class which takes some properties


from its base class.
 It is true that a pointer of one class can point to other
class, but classes must be a base and derived class,
then it is possible.
 To access the variable of the base class, base class

pointer will be used.


 So, a pointer is type of base class, and it can access

all, public function and variables of base class since


pointer is of base class, this is known as binding
pointer.
 In this pointer base class is owned by base class but

points to derived class object.


 Same works with derived class pointer, values is

changed.
Explain Virtual Functions and List the rules for virtual
functions.
C++ virtual function
o A C++ virtual function is a member function in the

base class that you redefine in a derived class. It is


declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic

linkage or late binding on the function.


o 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.
o A 'virtual' is a keyword preceding the normal
declaration of a function.
o When the function is made virtual, C++ determines
which function is to be invoked at the runtime based
on the type of the object pointed by the base class
pointer.
Rules of Virtual Function
o Virtual functions must be members of some class.
o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class,
even though it is not used.
o 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.
o We cannot have a virtual constructor, but we can
have a virtual destructor
6. Explain when to make a virtual function
“pure”?
Sometimes implementation of all function cannot be
provided in a base class because we don’t know the
implementation. Such a class is called abstract class. For
example, let Shape be a base class. We cannot provide
implementation of function draw() in Shape, but we
know every derived class must have implementation of
draw(). Similarly an Animal class doesn’t have
implementation of move() (assuming that all animals
move), but all animals must know how to move. We
cannot create objects of abstract classes.
A pure virtual function (or abstract function) in C++ is
a virtual function for which we can have
implementation, But we must override that function in
the derived class, otherwise the derived class will also
become abstract class (For more info about where we
provide implementation for such functions refer to
this https://stackoverflow.com/questions/2089083/pure
-virtual-function-with-implementation). A pure virtual
function is declared by assigning 0 in declaration
// An abstract class
class Test
{
public:
virtual void show() = 0;
};
True or false: A pointer to a base class can point to
objects of a derived class.
not true.
An object of the derived class is also a base class object,
so it can be pointed to by a base class pointer. However
, a base class object is not a derived class object, so it
cannot be assigned to a derived class pointer.
When you have a valid pointer pointing to a type, you
are saying that the object pointed to will have certain
data in certain locations so that we can find it. Derived
is guaranteed to have all the base data members in the
same locations , therefore, a pointer to bade can actually
point to derived.

Create a base class called shape. Use this class to


store two double-type values that could be used to
compute the area of figures. Derive two specific
classes called triangle and rectangle from the base
shape. Add to the base class, a member function
get_data() to initialize base class data members. and
another member function display_area() to compute
and display the area of figures. Make display_area()
as a virtual function and redefine this function in the
derived classes to suit their requirements. Using
these three classes, design a C++ program that will
accept dimensions of a triangle or a rectangle
interactively, and display the area. Area of
rectangle = L * L Area of Triangle = ½ * b * h
#include<iostream>
#include<iomanip>
using namespace std;
class shape
{
public:
double x,y;
public:
void get_data()
{
cin>>x>>y;

}
double get_x(){return x;}
double get_y(){return y;}
virtual void display_area(){}
};

class triangle:public shape


{
public:
void display_area()
{
double a;
a=(x*y)/2;
cout<<" Area of triangle = "<<a<<endl;

}
};
class rectangle:public shape
{
public:
void display_area()
{
double a;
a=x*y;
cout<<" Area of rectangle = "<<a<<endl;
}
};
int main()
{

shape *s[2];
triangle t;
s[0]=&t;
rectangle r;
s[1]=&r;
cout<<" Enter the value of x & y for triangle: ";
s[0]->get_data();
cout<<" Enter the value of x & y for rectangle: ";
s[1]->get_data();
s[0]->display_area();
s[1]->display_area();
return 0;
}
OUTPUT
Enter the value of x & y for triangle: 12 26

Enter the value of x & y for rectangle: 24 14

Area of triangle = 156

Area of rectangle = 336

Write a program to demonstrate how a Base class


object and derived class object can be accessed using
a pointer concept.
#include<iostream.h>
class base
{
public:
int n1;
void show()
{
cout<<”\nn1 = “<<n1;
}
};
class derive : public base
{
public:
int n2;
void show()
{
cout<<”\nn1 = “<<n1;
cout<<”\nn2 = “<<n2;
}
};
int main()
{
base b;
base *bptr; //base pointer
cout<<”Pointer of base class points to it”;
bptr=&b; //address of base class
bptr->n1=44; //access base class via base
pointer
bptr->show();
derive d;
cout<<”\n”;
bptr=&d; //address of derive class
bptr->n1=66; //access derive class via base
pointer
bptr->show();
return 0;
}
Output
Pointer of base class points to it
n1 = 44
Pointer of base class points to derive class
n1=66

You might also like