Archive

Posts Tagged ‘namespace std’

[C++ Tutorial 4] More on Namespaces

July 10th, 2010 1 comment

To see an introduction to what namespaces are, go back to tutorial 3. Now, cout is a function in the namespace "std". Now, there's another way of using cout without specifying the namespace before hand.

#include<iostream>
int main(
{

a
std::cout<<"Hello Jolly!";
system("pause");
return 0;
}

Here, std::cout means the cout that comes from the std namespace. However, since we would eventually use a large number of output and input statements(ie cout's and cin's), we would usually declare the namespace beforehand.

Creating our own namespaces

We can also create our own namespaces. These may contain a number of variables and functions to be used for the particular namespace. We here create a namespace called "my" with a variable of integer type called x.

We will be going into variables and data types in a few tutorials, but here's ow you create an integer variable called x-

int x;   //creates a variable called x
           //which takes integral values

So, here's our own namespace-

namespace my{   //creating a namespace
int x;
}
int main()
{
my::x;         //using the namespace variable
}

If we intend to use our variable x a number of times, we could specify our namespace in the program.

using namespace my;  //declare namespace beforehand