Saturday, May 26, 2007

Cpp tips

To Be done :
--------------------

1.make use of namespaces in C++ ( C++ filter class developement ...)

To avoid the naming conflicts.

2.Use Exception handling mechanisms in ur C++ class



1.explicit keyword :
-----------------------

namespace ExplicitTesting
{
class Stack
{
int size;

public:

//explicit keyword restricts user to pass the value to the constructor

explicit Stack(int nCount)
{
size = nCount;
}

};
}


int main(int argc, char* argv[])
{
ExplicitTesting::Stack s(10) ;

// ExplicitTesting::Stack st; //Gives error


return 0;
}


2.namespace keyword :
------------------------------

we can use the namespace in two ways;

namespace Test
{
void print()
{
printf("\n Hello world...");
}
}


the client usage1 :
-------------------------

Test::print();

the client usage 2:
-----------------------
using namespace Test;

and call the print() fn


3.Exception :
-----------------

You can specify which set of exceptions a function might throw by writing an exception specification:

void f() throw(bad_alloc); //f() may only throw bad_alloc exceptions

You can specify that a function not throw an exception by declaring an empty set of exceptions:

void f() throw(); //f() does not throw

4. For boolean operations use bool data type in C++

5.Operators for Type Conversion in C++
--------------------------------------------------

1.static_cast<>
2.dynamic_cast<>
3.const_cast<>
4.reinterpret_cast<>

static_cast<> :

This operator converts a value logically. It can be considered a creation of a temporary object that is initialized by the value that gets converted.. For example:

example for static casting :
----------------------------------
float x;
...
cout << static_cast(x); // print x as int ...
f(static_cast("hello")); // call f() for string instead of char


double f(100.10);

printf("%d",static_cast(f));


double f(100.10); is equaivalent to the double f = 100.10;

No comments: