Namespace
Namespace
What is namespace?
Also explain nested namespace and unnamed namespace.
C++ introduced a
new keyword ‘namespace’ to define a scope that could hold global identifiers.
The best example of namespace is the C++ standard library. Where all the
classes, functions and templates are declared within the namespace ‘std’. hence
while writing a C++ program, we usually include the directive
Using namespace
std
The statement
‘using namespace std’ specifies that the members defined in the ‘std’ namespace
will be used in the program very frequently.
Syntax:
Namespace
name_of_namespace
{
//declarations of variables, functions,
classes etc.
}
Example
using
namespace std;
namespace
s
{
int a=6;
void display();
{
cout<<"hello";
}
}
int
main()
{
using namespace s;
cout<<a<<endl;
display(); return
0;
}
Nested namespace
C++
allows nesting of a namespace within another namespace as shown in the example
below.
Example:
Namespace
A
{
Int x;
Namespace B
{
Int y;
}
}
The
variable of nested namespaces can be accessed, using the following statement.
A::B::y=2;
Or
using namespace A;
B::y=2;
Unnamed namespaces:
Unnamed
namespaces are also called anonymous namespace. As the name indicated, unnamed
namespaces are those namespaces which do not have a name. The members of
unnamed namespace occupy the global scope and are accessible in all scopes
following the declarations in the file.
Syntax
Namespace
{
//declarations of variables, functions,
classes etc.
}
Mutable data
member.
Whenever a
member function is made constant, it cannot modify the data member of its class
but, if the need arises, such that, the constant member functions has to modify
the value of the data member, then the data member has to be declared by prefixing
the keyword ‘mutable’ as shown below.
mutable int x=5;
Explain Set_new_handler.
Ø When the operator new cannot find a contiguous block
of memory large enough to hold the desired object at this point a special
function called the set_new_handler() is called.
Ø There is an internal function pointer ‘_new_handler’,
which usually contains a NULL value, which is called by the “new” when it fails
and hence the failed ‘new’ operator returns a NULL value. Now instead of a NULL
value, We can point the ‘_new_handler’ function pointer to any user-defined
function so that next time when ‘new’ fails the user defined function is
called. To make the ‘_new_handler’ function pointer point to some user-defined
function definition, C++ provides a built in function by name
‘set_new_handler()’ function.
Ø The ‘set_new_handler’ function returns the old
handler, if it has been defined by default, no handler is installed. It is very
important to note that the user defined function or ‘my_handler()’ should not return a value and should not take
any argument.