Btechadda.com

Archive for January, 2010

Static Members

by hkesavaraju on Jan.28, 2010, under Advanced Data Structures

Static Members:

The static members can be static data members or static member functions.

(continue reading…)

Leave a Comment more...

Dynamic Memory allocation and deallocation

by hkesavaraju on Jan.28, 2010, under Advanced Data Structures

Dynamic Memory allocation and deallocation

In c, malloc() and calloc() are used to allocate memory dynamically and free() to remove allocated memory space. These are needed to allocate enough memory when it is not known in advance. This is called Dynamic Memory Management technique. Although C++ supports these, it uses two unary operators new and delete for performing allocation and deallocation respectively. These operators are called free store operators because they manipulate memory on free store.

new: The object can be created using new operator and removed using delete as and when required. An object is created within a block with new which remain in existence until it is destroyed using delete.

new operator is used to create an object of any type. its syntax is

pointer_variable=new datatype;

pointer_variable is a pointer of type datatype. new operator allocates enough memory required for an object of datatype and returns address of the object. The data type can be any valid type.

The example pointers are:

int *p;

int *q;

The above two are integer pointers. They are created with new are:

p=new int;

q=new int;

These two pointers are declared in below statement are:

int *p=new int;

int *q=new int;

The following assignments are valid:

*p=5;

*q=15;

(i) new is allowed to initialize the memory. In such case, it passes initial value to data type.

*p=new int(5); // it assigns initial value 5 to *p

(ii) new is used to create an object of any type including user defined data types such as arrays, structures and classes.

(iii) new is used to create one dimensional array. The general syntax is:

pointer_variable=new datatype[size];

where size specifies the number elements in the array.

The example is *p=new int[10].It creates an integer pointer consists of 10 locations. p[0] refer the first element ,p[1] refers the second element and so on.

  1. new can also used to create multi dimensional array. The examples for it are:

*p=new int[3][4][5]; //legal

*p=new int[m][4][5]; //legal

*p=new int[][4][5]; //illegal

*p=new int[3][4][]; //illegal

When the first dimension is a variable, its value must ne supplied at run time.

(vi) It is always good to test whether pointer variable allocated in memory or not.

p=new int;

if(!p )

{

cout<<”allocation failed \n”;

}

(vii) The new operator has many advantages over malloc ().They are:

{i} It computes the size of the object without using sizeof().

{ii} It returns correct pointer type without using any type cast.

{ii} It initializes the object while creating the memory space.

{iv} It can overloaded like any other c++ function.

delete: When objects are no longer needed, they must be destroyed to release the memory for reuse. The general form of delete is:

delete pointer_variable;

pointer_variable is the pointer that points to a data object created with new.

Examples include:

delete p;

delete q;

  1. delete is used to deallocate dynamic allocated array, its syntax is

delete [size]pointer_variable;

size specifies number of elements in the array are deallocated .The problem with is programmer must remember array size.

In recent versions of c++, size is not required. it is like

delete []pointer_variable;

A question arises memory allocated to the object when it is created but not when defining class specification. It is partly true. When functions are created in a class, they occupies some space in memory. There are so many objects for a class, each one uses same member functions and no separate memory required for all because they are all belongs to same class. Only space for variables is allocated separately for each object.

Leave a Comment more...

Exceptions

by hkesavaraju on Jan.28, 2010, under Advanced Data Structures

Exceptions

It is rare that a program runs correctly at very first time. It may have bugs like syntax and logical errors. It is possible to come across peculiar problems rather than syntax or logical errors is exceptions. An exception is an anomaly or unusual condition that terminates program execution abnormally. The anomalies are divide by zereo, referring to array in outside, running out of space or overflow.

Types of Exceptions: There are 2 types of exceptions called synchronous and asynchronous errors. The synchronous exceptions are out of range index and overflow errors. The errors that are caused by the events beyond the control of the program are called asynchronous errors.

The exceptional handling is a mechanism that detects the problem and takes corrective measures to handle it. It involves the following tasks.

  1. Hit exception ( find the problem)

  2. Throw the exception (inform the error information)

  3. Catch the exception ( receive the message)

  4. Handle the exception ( Take appropriate action)

1.11.2 Basics of Exceptional Handling: The C++ exceptional handling is processed by using three key words try, catch and throw. try preface a block of statement which generates the exception. this is called try block. An exception is raised explicitly by using throw in try block. The catch block caught the exception thrown in try block and handles it. The relationship of try and catch is shown below.

The general syntax of try and catch is as follows:

try

{

  • - – -

throw(object);

  • —-

  • - – -

}

catch(type arg)

{

- – - – // code that handles the exception

}

When an exception is raised in try, the control leaves try and goes to catch block which immediately follows it. If object type thrown and type of argument catch block matches, then catch block is executed. If not, program execution terminates abnormally by invoking abort().After catch block is completed, the control goes to the immediate statement after catch block. If exception is not raised in try, catch block is skipped; the statement after catch is executed.

An example is:

#include<iostream.h>

#include<conio.h>

main()

{

clrscr();

int a,b,x;

cout<<”enter a & b values”;

cin>>a>>b;

x=a-b;

try

{

if(x!=0)

{

r=a/x;

cout<<”\n result is”<<r;

}

else

throw x;

}

catch(x)

{

cout<<”\n exception caught”<<x;

}

}

the output is:

First case is : enter a &? b values 10 5

result is 2

Second case is: enter a & b values 10 10

exception caught 0

An exception can also be raised by invoking a function within try block. The point at which an exception is raised called throw point. Once exception thrown to catch, the control never returns to try again.

function

An example is:

#include<iostream.h>

#include<conio.h>

void fun(int x,int y,int z)

{

cout<<”we r inside the function”;

if(x-y!=0)

{

cout<<”\n division of z & x-y is”<<z/(x-y);

}

else

throw (x-y);

}

}

main()

{

clrscr();

try

{

cout<<”we are inside try”;

fun(10,5,40);

fun(10,10,40);

}

catch(int i)

{

cout<<“\n exception caught”

}

}

the output is:

we are inside try

we r inside function

division of z & x-y is 8

we r inside function

exception caught

1.11.3 Throwing Exceptions: The keyword throw can be in more than one form. They are:

throw(exception) // it passes exception object as parameter to catch

throw exception;

throw; It means throw without any argument is used to rethrow the exception without processing it. It causes exception is thrown to next enclosing try/catch in sequence.

1.11.4 Catching mechanism: A catch block is invoked like a normal function and has the following general form:

catch(type arg)

{

// code to handle the exception

}

The argument arg is optional parameter name. The type of argument when matched with type of exception thrown, catch block is executed and goes to execute the statement after the catch block.

When the arg name is specified in the parameter, then it is used to handle the exception.

  1. Multiple catch statements: When program segment has more than one condition to throw the exceptions.Then,more than one catch block is provided to try block.

The general form of multiple catch statements is:

try

{

// raise more than one exception

}

catch(type1 arg)

{

//catch1 code

}

catch(type2 arg)

{

//catch2 code

}

.. .. .. . …

. . . . . . . .

catch(typeN arg)

{

// catchN code

}

When exception is thrown in try, it can be searched in order from immediate catch block after try. If any one of catch block’s argument is matched with type of exception thrown in multiple catch handlers, then the catch block which is matched is executed. All of the remaining catch blocks is skipped and goes to execute statement after last catch block.

If the type of exception thrown is matched with more than one catch block, then first catch block which matched is executed.

An example is:

#include<iostream.h>

#include<conio.h>

void test(int x)

{

cout<<”\n inside function”;

try

{

if(x==1) throw x;

else if(x==0) throw ‘x’;

else if(x==-1) throw 1.0;

cout<<”\n end of try block”;

}

catch(int i)

{

cout<<”\n caught integer”;

}

catch(char i)

{

cout<<”\n caught character”;

}

catch(double i)

{

cout<<”\n caught double”;

}

cout<<”\n end of try catch blocks”;

}

main()

{

clrscr();

cout<<”multiple catch choices\n ”;

test(1);

test(0);

test(-1);

test(2);

getch();

}

The output is: multiple catch choices

inside function

caught integer

end of try catch blocks

inside function

caught character

end of try catch blocks

inside function

caught double

end of try catch blocks

inside function

end of try block

end of try catch blocks

In this, main() calls test(1) first, test function is invoked and throw x is executed in try and caught by catch(int i) block. main() calls test(0) secondly, test is invoked and throw ‘x’ is executed and is caught by

catch(char i) block. main() next calls test(-1) which executes throw 1.0 and is caught by catch(double i) block.Then,main() next calls test(2) which doesn’t throw any exception in try but executes cout<<”end of try block” in try.

  1. catch all exceptions: There is a catch block with ellipses as argument is used for handling any type of exception thrown instead of a certain type.The general form of catch all exceptions is:

catch(. . .)

{

//code to handle any type of exception

}

An example that illustrates catch(…) is as follows:

#include<iostream.h>

#include<conio.h>

void test(int x)

{

try

{

if x==1 throw x;

if x==0 throw ‘x’;

if x==-1 throw 1.0;

}

catch(…)

{

cout<<”exception caught”;

}

}

main()

{

clrscr();

test(1);

test(0);

test(-1);

getch();

}

the output is: exception caught

exception caught

exception caught

Irrespective of type of exception raised in try, a single catch() block is used to handle them.

1.11.5 Specifying exceptions: It is possible to restrict a function to throw certain specified exceptions. This can be achieved by adding a throw list to the function definition. The general syntax of using exception specification is:

return_type function_name(arg_list) throw(type_list)

{

// function body

}

The function can only throw types specified in throw() list. if Any other type is thrown, program execution terminates. The function can be prevented from throwing any exception using throw list as throw().

An example is:

#include<iostream.h>

#include<conio.h>

void test(int x) throw(int,double)

{

if(x==0) throw ‘x’;

else if(x==1) throw x;

else if(x==-1) throw 1.0;

cout<<”end of try block”;

}

main()

{

clrscr();

try

{

cout<<”throwing restrictions”;

test(0);

test(1);

test(-1);

}

catch(char c)

{

cout<<”caught character”;

}

catch(int i)

{

cout<<”caught integer”;

}

catch(double k)

{

cout<<”caught double”;

}

cout<<”end of try catch blocks”;

}

The output is: throwing restrictions

caught character

end of try catch blocks.

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...