In the last post we discussed the concept of Dynamic memory and new, delete operators. today we'll discuss some other C++ concepts.
Including User Defined Header Files:
Uptil now we have only seen examples where we use C++ standard library header files. these are included according to the following mechanism.
when including our own header files C++ the following mechanism is used:
an example is given below:
Namespaces:
A C++ program has identifiers in different scopes, Sometimes these scopes overlap which can lead to problems;
• So to counter this we have Namespaces, which define scope
–
Place identifiers and variables within namespace
–
Access with namespace_name::member
–
Unnamed namespaces are global
•
Need no qualification
–
Namespaces can be nested
•
using statement
–
using namespace namespace_name;
–
Members of that namespace can be used without
preceding namespace_name::
•
Can also be used with individual member
–
Examples
•
using namespace std
•
Discouraged by some programmers, because
includes entire contents of std
•
using namespace std::cout
•
Can write cout instead of std::cout
Consider the following examples:
Example 1:
#include
<iostream>
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main ()
{
using first::x;
using second::y;
cout
<< x << endl;
cout << y << endl;
cout
<< first::y << endl;
cout
<< second::x << endl;
return 0;
}
Properties of Namespaces:
We
can have more than one namespace of the same name. This gives the advantage of
defining the same namespace in more than one file (although they can be created
in the same file as well). The
“anonymous” namespace you have created will only be accessible within the file
you created it in.
Typedef:
typedef is a Keyword which:
–Makes
synonyms (aliases) for previously defined data types
•Does
not create new type, only an alias
–Creates
shorter type names
Example:
–typedef int* intPtr;
–Defines
new type name intPtr
as synonym for type int*
•intPtr myintPtr;
•int * myintPtr; //Both are same
Bitwise Operators:
Data is represented internally as sequences of bits
–
Each bit can be 0 or 1
–
8 bits form a byte
•
char is one byte
•
Other data types larger (int, long,
etc.)
–
Low-level software requires bit and byte
manipulation
•
Operating systems, networking
• So for bit and byte manipulation we have "Bit operators", these contain:
–
& (bitwise AND)
•
1 if both bits 1, 0
otherwise
–
| (bitwise inclusive OR)
•
1 if either bit 1, 0
otherwise
–
^ (bitwise exclusive OR)
•
1 if exactly one bit is 1, 0
otherwise
•
Alternatively: 1 if the bits are
different
–
~ (bitwise one's complement)
•
Flips 0 bits to 1, and vice versa
–
<< (left shift)
•
Moves all bits left by specified amount
•
Fills from right with 0
•
int x = 16;
•
x = x << 2;
–
>> (right shift with sign
extension)
•
Moves bits right by specified amount
•
Fill from left can vary
Post a Comment