You cannot copy content of this page.

Monthly Archive May 2013

Exception handling and its classification in C++



Exception handling and its classification in C++

Exception Handling:  The error handling mechanism of C++ is generally referred to as exception handling.  C++ provides a mechanism of handling errors in a program.

Generally exceptions are classified into synchronous and asynchronous exceptions.

  1. Synchronous Exceptions:  The exceptions which occur during the program execution due to some fault in the input data or technique that is not suitable to handle the current class of data, within the program are known as synchronous exceptions.  For example: errors such as out of range, overflow, underflow and so on belong to the class of synchronous exceptions.
  2. Asynchronous Exceptions:  The exceptions caused by events or faults unrelated (external) to the program and beyond the control of the program are called asynchronous exceptions.  For example: errors such as keyboard interrupts, hardware malfunctions, disk failure and so on belong to the class of asynchronous exceptions.

The exception handling mechanism of C++ is designed to handle only synchronous exceptions within a program.

This is done by throwing an exception.  The exception handling mechanism uses three blocks: try, throw and catch.  The try-block must be followed immediately by a handler, which is a catch block.  If an exception is thrown in the try block, the program control is transferred to the appropriate exception handler.  The program should attempt to catch any exception that is thrown by any function.  Failure to do so may result in abnormal program termination.

Exception Handling Constructs:

(1)  throw:- The keyword throw is used to raise an exception when an error is generated in the computation.

(2)  catch:-  The exception handler is indicated by the catch keyword.  It must be used immediately after the statements marked by the try keyword.

(3)  try:-  The try keyword defines the boundary within which an exception can occur.

Thus, the error handling code must perform the following tasks:-

  1. Detect the problem causing exception. (Will hit the exception).
  2. Inform that an error has occurred.  (Throw the exception).
  3. Receive the error information (Catch the exception).
  4. Take corrective actions. (Handle the exception).


For example:  (Divide operation validation)

int division(int n1, int n2)
{
if(n2==0)
throw n2;
else
return n1/n2;
}

int main()
{
————
————
————
try
{
result=division(n1,n2);
}
catch(int)//exception handler block
{cout<<”Exception raised! Division Error…!”;
return -1;
}
————
————
}

 

Tags

Syntax for creating user defined manipulators in C++




Syntax for creating user defined manipulators in C++

C++ provides a set of predefined manipulators. The header file iomanip.h header file contains these manipulators. Moreover, you can design your own manipulators in C++ to suit specific purpose. The user defined manipulators are defined as follows:

ostream & manipulator(ostream & ostr)
{
set of statements;
return ostr;
}

Consider the following example which creates a user defined manipulator named curr for displaying Rs. and sets the precision to 2.

#include <iostream.h>
#include <iomanip.h>

ostream & curr(ostream & ostr)
{
cout<< setprecision(2);
cout<<“Rs. “;
return ostr;
}

void main()
{
float amt = 4.5476;
cout<<curr<<amt;
}

//Output: Rs. 4.55

 

Tags

Use of manipulators in C++




Use of manipulators in C++

Manipulators are stream functions available in iomanip.h header file and are used to change the default formats of input and output.  These are used with stream insertion and extraction operators.  They are used for defining a specified format of input and output.  They provide features similar to that of ios member functions.  Moreover, manipulators may be concatenated to result in a single statement.  Some of the standard manipulators available in iomanip.h header file are endl, setw, setfill, hex, oct, dec, setprecision, flush, setiosflags etc.  Manipulators are different from ios member functions as manipulator does not return the previous format state as is the case with ios member functions.

Consider the following example:

#include <iostream.h>
#include <iomanip.h>

void main()
{
float x = 5.45;
cout<<setw(10);
cout<<setprecision(4);
cout<<setfill(‘*’);
cout<<x<<endl;
}

OUTPUT:

******5.45

Consider another example:

#include <iostream.h>
#include <iomanip.h>

void main()
{
int n=52; //decimal number
cout<<endl<<“Decimal Number=”<<dec<<n;
cout<<endl<<“Hexadecimal Number=”<<hex<<n;
cout<<endl<<“Octal Number=”<<oct<<n;
}

Output:

Decimal Number=52
Hexadecimal Number=34
Octal Number=64

Tags

Template class in C++



Template class in C++

A class which is declared such that it can operate on different data types is referred to as a template class.  It is a generic class defined to support various similar operations on different data types.  For example: a class may be created with a data member, such that it can operate upon any type of data member either int, float or char or any other type.  Whenever we require to generalize the definition of a class for various data types used in C++, we may prefer using class templates, as it gives a more general definition for a class.

To declare a template class, we have to use the keyword template followed by class name i.e. template <class nmofclass>, where template and class are keywords and nmofclass is the userdefined name given to a generic class definition. 

An example to illustrate the use of template class is given below:

template <class sample>
class abc
{
sample x;
public:
void getx(){cout<<”Enter x?”;cin>>x;}
void putx(){cout<<”x=”<<x;}
};

The data type is specified when the object of the class is created in the manner specified below:

abc <int> obj1;
// class that contains an int variable.
abc <float> obj2;
// class that contains a float variable.

The complete program is as follows:

#include <iostream.h>
#include <conio.h>

template <class sample>

class abc
{
sample x;
public:
void getx()
{
cout<<“\nEnter x?”;
cin>>x;
}
void putx()
{
cout<<“\nx=”<<x;
}
};

void main()
{
clrscr();
abc <int> obj1;
cout<<“\nWorking on integer…!”;
obj1.getx();
obj1.putx();

abc <float> obj2;
cout<<“\n\nWorking on float…!”;
obj2.getx();
obj2.putx();
getch();
}

Thus class templates are required to create generic classes that can refer to any user-defined data type.

 

Tags

How is polymorphism achieved at compile time in C++




How is polymorphism achieved at compile time in C++

Polymorphism, in C++, is implemented through overloaded functions and overloaded operators. Function Overloading is also referred to as functional polymorphism. The same function can perform a wide variety of tasks. The same function can handle different data types. When many functions with the same name but different argument lists are defined, then the function to be invoked corresponding to a function call is known during compile time. When the source code is compiled, the functions to be invoked are bound to the compiler during compile time, as to invoke which function depending upon the type and number of arguments. Such a phenomenon is referred to early binding, static linking or compile time polymorphism.

For example:

#include <iostream.h>

//function prototype

int multiply(int num1, int num2);
float multiply(float num1, float num2);

void main()
{
//function call statements

int ans1=multiply(4,3);
// first prototype is invoked as arguments
// are of type int

float ans2 = multiply(2.5, 4.5);
//second prototype is invoked
//as arguments are of type float
}

The compiler checks for the correct function to be invoked by matching the type of arguments and the number of arguments including the return type. The errors, if any, are reported at compile time, hence referred to as compile time polymorphism.

Tags

Concept of Polymorphism in C++



Concept of Polymorphism in C++

Polymorphism is one of the most important features of Object Oriented Programming.  Polymorphic variables can take up objects or values of different types as values and polymorphic functions and procedures can be used as objects or values of different types.  It refers to exhibiting different behaviour by an instance in different situations.  Polymorphism is implemented through function overloading and operator overloading.  Overloading is a form of polymorphism.  In case of function overloading, the information regarding which function is to be invoked corresponding to a function call is available at compile time.  This is referred to as static binding or compile time polymorphism, as the object is bound with its function call at compile time.

 

Run time polymorphism is achieved through virtual functions.  The function to be invoked by the instance of a class is known during runtime.  The functions are linked with the class during runtime and not during compile time.  When a base class pointer points to a sub class instance, instead of invoking subclass function (a function having name similar to that of function of a base class), it always invokes base class version.  If the function in the base class is defined as virtual, then it is known during runtime only, which version of the function will be invoked, corresponding to a function call.  Since the function is linked after compilation process, it is termed as late binding or dynamic binding or run-time polymorphism

Tags

Difference between a Virtual function and Overloaded function in C++




Difference between a Virtual function and Overloaded function in C++

C++ supports dynamic linking through virtual functions. Whenever both the base class and derived class have function with the same name, then the base class function always invokes the base class function irrespective of the fact that it is pointing to the derived class function. When a function is defined as virtual, it is determined at runtime, which function to use depending upon the type of object pointed to by the base class pointer. Thus, if a base class pointer points to different objects of different classes, by defining base member function as virtual, we can invoke different versions of different function.

Function Overloading is the phenomenon of defining different functions with the same name but different function signatures i.e. we can use same function name to perform a wide variety of tasks on different data types. The function to be invoked is determined by the number and type of arguments. Hence in function overloading the function prototypes differ and are not identical.

If the prototypes of the virtual function defined in the base class, and all other functions defined in derived classes is identical then they are considered as virtual functions. If the two functions with the same name have different prototype, then they are considered as overloaded functions and the virtual function phenomenon is ignored irrespective of the virtual function.

Tags

Pure Virtual Functions in C++




Pure Virtual Functions in C++

A Pure Virtual Function is a virtual function that is initialised to zero and has no definition in the base class.  Such functions are merely included in the base class, but do not perform any task.  A pure virtual function is also referred to as a do-nothing function.  Such a function is defined separately in all derived classes and its definition in the base class is not required.  The compiler, in case of a pure virtual function, requires each derived class to either define the function or re-declare it as a pure virtual function.  Such a class which contains a pure virtual function cannot be instantiated,  is referred to as an abstract class.


Consider the following code segment:

class base
{
public:
virtual void show_output() = 0;
//a pure virtual function declared
//and initialized to zero.
};

class derived : public base
{
public:
void show_output()
//function re-defined in derived class.
{
cout<<”Inside show_output function.”;
}
};

As the presence of a pure virtual function in a class requires that it should be implemented in derived classes, in the above code segment show_output() function in class ‘base’ is defined as virtual and is initialized with zero, so it is a pure virtual function.  Class ‘derived’ is publicly inherited from class ‘base’.  Class ‘base’ is an abstract base class, as it includes a pure virtual function.

 

Tags

Difference between containership and inheritance in C++



Difference between containership and inheritance in C++

Containership:  Containership is the phenomenon of using one or more classes within the definition of other class.  When a class contains the definition of some other classes, it is referred to as composition, containment or aggregation.  The data member of a new class is an object of some other class.  Thus the other class is said to be composed of other classes and hence referred to as containership.  Composition is often referred to as a “has-a” relationship because the objects of the composite class have objects of the composed class as members.


Inheritance:  Inheritance is the phenomenon of deriving a new class from an old one.  Inheritance supports code reusability.  Additional features can be added to a class by deriving a class from it and then by adding new features to it.  Class once written or tested need not be rewritten or redefined.  Inheritance is also referred to as specialization or derivation, as one class is inherited or derived from the other.  It is also termed as “is-a” relationship because every object of the class being defined is also an object of the inherited class.

 

Tags

Difference between a Virtual class and an Abstract class in C++




Difference between a Virtual class and an Abstract class in C++

Virtual Class: A virtual class is one that has been qualified as virtual in the inheritance definition.  When a derived class inherits from more than one base class, then it can inherits the members of a base class from multiple inheritance paths. If the base class is defined as virtual, only one copy of the members of the base class is inherited by the derived class irrespective of the fact that it can be inherited from a number of inheritance paths.

 

Abstract Class: An abstract class is one, which is never instantiated.  The objects of an abstract base class are never created.  A base class that contains pure virtual functions is an abstract base class.  A pure virtual function is a virtual function that has no implementation in its class.  Thus an abstract class provides a base upon which to build other classes.  It is designed only to act as a base class for other classes and it is not used to create objects.  Thus an abstract base class provides some transit to the derived classes and is never initiated.

Tags

x Close

Like Us On Facebook