Tuesday, May 11, 2010

Unexpected Exception

How to specify Exception?
 func()                    // this can throw any Excpeption
 func()  throw()      // this Will NOT throw any Excpeption
 func()  throw (bad_alloc , X )  // this can throw only specified  Excpeption

unexpected() is called when function throws exception other  than specified 

It uses     _unexpected_handler  which can be changed  
unexpected_handler old_hand  = set_unexpected( newfunction);
 
void newfunction( ) 
{
   cout << "Hi" << endl;
   terminate( );
}
 

Sunday, May 9, 2010

Auotmatic Type Conversion and use of Explicit Keyword

1. By Constructor Conversion :
        See this situation .

Output :
Constructor B called
Hi inside Function
--------------------------------------------------------------------------------
Preventing constructor conversion.
This Behaviour of automatic calling of constructor . can be stopped if constructor is explicit.
Explicit Constructor: Constructor with explicit keyword.It prevents compliler from performing implicit (Unexpected) type conversions.


After this   func (a); will not get compiled .

Output:Compliation Fails
auotTypeConversion.cpp: In function `int main()':
auotTypeConversion.cpp:18: error: conversion from `A' to non-scalar type `B' requested

2. Operator Conversion :

OUTPUT:
inside conversion operator B--> A
inside A constructor i=10
Function call

Saturday, May 8, 2010

Exception Handling

Q How to catch all type of Exception ?
Ans Three dots try { } catch(...)
three dots is called   Ellipsis

Friday, May 7, 2010

When to return const refrence ?

a)When do we return by refrence?
Ans:. it avoids copying . But never return reference of local object .
     So that functions can be l-values
     We do this when we want to modify  lvalue  . we do this in operator overlaoding of " ="  to support a=b=c  chaining 
MyClass & operator=(const MyClass &rhs);
MyClass & operator+=(const MyClass &rhs) 
 
b) Returning just const
As const return can be assigned to nonconst variable and changed .
But if function is used in expression then temporary return as it is const will be prohibited .
struct foo
{
void bar() {}
void barfoo() const {}
};

foo foobar1() {return foo();}
const foo foobar2() {return foo();}

int main()
{
foobar1().barfoo(); //perfectly legal, calling const member function of non-const object
foobar1().bar(); //perfectly legal, calling non-const member function of non-const object
foobar2().barfoo(); // perfectly legal, calling const member function of const object
foobar2().bar(); // this willl not compile
}

In operator overloading we use it often to make sure
const MyClass MyClass::operator+(const MyClass &other) const


(a+b)=c // this kind of things will not get compile
We make sure (a+b).func()  is allowed only if func()is const function .
this is called const correectness

c)When to return const refrence
This make lot of sense .


http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html

Followers