DISHA NIRDESHAN

Enlightens your career

Tuesday, June 21, 2011

Questions on Exceptional handling & polymorphism


 

EXCEPTION HANDLING:

What is an Exceptional Handling?

An exception is a hardware generated condition which is triggered when processing fails for some reason in a CPU. It could be caused by dividing by zero or trying to access memory at a nonexistent address

The exception handling mechanism is made up of the following elements:

 

ü try blocks

ü catch blocks

ü throw expressions

ü Exception specifications (C++ only)

 

The benefits of Exception Handling are:

1. Program is not terminated abruptly
2. User will understand what errors are occurring in the program.

The three keywords for Exception Handling are:
Try, Catch and Throw.

The program tries to do something. If it encounters some problem, it throws an exception to another program block which catches the exception.

 

Consider following program code:
void main()
{
               int no1, no2;
               try
               {
                       cout << "Enter two nos:";
                       cin >> no1 >> no2;
                       if (no2 == 0)
                              throw "Divide by zero";
                       else
                              throw no1/no2;
               }
               catch (char *s)
               {
                          cout << s;
               }
               catch (int ans)
               {
                          cout << ans;
               }
}

We know that divide by zero is an exception. If user enters second no as zero, the program throws an exception, which is caught and an error message is printed.

After an exception has been handled the program execution resumes after the try-catch block, not after the throw statement!.

 

 

Explain about Rethrowing exceptions with an example.  

Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no exception. This causes current exception to be passed on to an outer try/catch sequence. An exception can only be rethrown from within a catch block. When an exception is rethrown, it is propagated outward to the next catch block.

Consider following code:

#include <iostream>
using namespace std;
void MyHandler()
{
        try
        {
                 throw "hello";
        }
        catch (const char*)
        {
               cout <<"Caught exception inside MyHandler\n";
               throw; //rethrow char* out of function
        }
}
int main()
{
            cout<< "Main start";
            try
            {
                   MyHandler();
            }
            catch(const char*)
            {
                  cout <<"Caught exception inside Main\n";
            }
                  cout << "Main end";
            return 0;
}
O/p:
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
Thus, exception rethrown by the catch block inside MyHandler() is caught inside main();

 

What are the tow types of Exceptions?

Exceptions are of two types:

Synchronous Exceptions: Errors that occur due to incorrect input data or incorrect handling of array indices ("out of range index"), memory overflow are known as Synchronous Exceptions

Asynchronous Exceptions: The errors that are caused by events that are beyond control of the program are Asynchronous Exceptions. E.g. Keyboard interrupts

C++ exception handling mechanism takes care of only Synchronous Exceptions.

 

 

 

 

 

 

POLYMORPHISM:

What is Polymorphism?

 

Polymorphism is the ability to provide single interface to multiple implementation it may be for an or function in different ways. Polymorphism gives different meanings or functions to the operators or functions. A single function usage or an operator functioning in many ways can be called polymorphism. Polymorphism refers to codes, operations or objects that behave differently in different contexts.
There are two types of polymorphism
1. Compile Time Polymorphism (Static Polymorphism)
2. Run Time Polymorphism (Dynamic Polymorphism)

1. Compile time polymorphism

Compile time polymorphism is a term that refers to C++ template programming. For example, at compile time you determine the actual type of a std::vector by what it contains:

std::vector  vi;
std::vector std::string> vs;

or function Overloading is the example of compile time polymorphism

2. Run Time Polymorphism (Dynamic Polymorphism)
Virtual function is the example of Run Time polymorphism. At the run time base class pointer decide whether to call the base class function or the derived class function.

 

 

How is it that polymorphism enables you to program "in the general" rather than "in the specific." Discuss the key advantages of programming "in the general." ?

Polymorphism enables the programmer to concentrate on the processing of common operations that are applied to all data types in the system without going into the individual details of each data type. The general processing capabilities are separated from the internal details of each type.

 

Discuss the problems of programming with switch logic. Explain why polymorphism is an effective alternative to using switch logic. ?

The main problem with programming using the switch structure is extensibility and maintainability of the program. A program containing many switch structures is difficult to modify. Many, but not necessarily all, switch structures will need to add or remove cases for a specified type.

Encapsulation:

What is Encapsulation?

1. The wrapping up of data and member function into a single unit is called encapsulation.

2. The data is not accessible to the outside world and only those functions which are wrapped into a class can access it.

                                      Or

Encapsulation is binding of attributes and behaviors. Hiding the actual implementation and exposing the functionality of any object. Encapsulation is the first step towards OOPS, is the procedure of covering up of data and functions into a single unit (called class). Its main aim is to protect the data from outside world

 

 

 

 Adding a new method with the same name in same/derived class but with different number/types of parameters. It implements Polymorphism.

 

What is Abstraction?

Hiding the complexity. It is a process of defining communication interface for the functionality and hiding rest of the things.


What is Overloading?

Specifying  more than one definition for a function name or an operator in the same scope is called Overloading

There are tow types of Overloading:

ü Operator overloading

ü Function Overloading

 

Operator overloading

One of the nice features of C++ is that you can give special meanings to operators, when they are used with user-defined classes. This is called operator overloading. You can implement C++ operator overloads by providing special member-functions on your classes that follow a particular naming convention. For example, to overload the + operator for your class, you would provide a member-function named operator+ on your class.

The following set of operators is commonly overloaded for user-defined classes:

  • = (assignment operator)
  • + - * (binary arithmetic operators)
  • += -= *= (compound assignment operators)
  • == != (comparison operators)

 

Function Overloading

It is a feature of C++ that allows us to create multiple functions with the same name, so long as they have different parameters. Consider the following function:

1

int Add(int nX, int nY)

2

{

 

3

    return nX + nY;

4

}

This trivial function adds two integers. However, what if we also need to add two floating point numbers? This function is not at all suitable, as any floating point parameters would be converted to integers, causing the floating point arguments to lose their fractional values.

One way to work around this issue is to define multiple functions with slightly different names:

1

int AddI(int nX, int nY)

2

{

 

3

    return nX + nY;

4

}

 

5

 

6

double AddD(double dX, double dY)

 

7

{

8

    return dX + dY;

 

9

}

However, for best effect, this requires that you define a consistent naming standard, remember the name of all the different flavors of the function, and call the correct one (calling AddD() with integer parameters may produce the wrong result due to precision issues).

Function overloading provides a better solution. Using function overloading, we can declare another Add() function that takes double parameters:

1

double Add(double dX, double dY)

2

{

 

3

    return dX + dY;

4

}

We now have two version of Add():

1

int Add(int nX, int nY); // integer version

2

double Add(double dX, double dY); // floating point version

Which version of Add() gets called depends on the arguments used in the call — if we provide two ints, C++ will know we mean to call Add(int, int). If we provide two floating point numbers, C++ will know we mean to call Add(double, double). In fact, we can define as many overloaded Add() functions as we want, so long as each Add() function has unique parameters.

Consequently, it's also possible to define Add() functions with a differing number of parameters:

1

int Add(int nX, int nY, int nZ)

2

{

 

3

    return nX + nY + nZ;

4

}

Even though this Add() function has 3 parameters instead of 2, because the parameters are different than any other version of Add(), this is valid.

 

 

 

 

What is Overriding ?

A process of creating different implementation of a method having a same name as base class, in a derived class. It implements Inheritance.

 

 


0 comments :