Thread: return types
View Single Post
Old 12-28-2004, 03:47 PM   #7 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Quote:
Originally Posted by sde
:: is the same as -> in php (classes)
Most likely not. :: is a scope resulution operator.
:: isn't chosen because of it looks by the way. Those who studied quantor mathematics should recognize this operator.
Anyway, it is the scope resolution operator, and we're going to have some fun with it. First the basics. Observe the code below and draw your own conclusions:
Code:
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

//(auto generated) Optional function: depends on IDE. Remove if not needed.
void wait_for_enter();

//On-topic code below!

string whoAmI = "I am a global: usually a prime example of bad coding.";

namespace sde
{
  string whoAmI = "I am sde: the big boss!";
}

namespace Val
{
  string whoAmI = "I am Val: a slave of sde :)";
}

namespace falsepride
{
  string whoAmI = "I am falsepride: I'm looking at mumbo jumbo...";
}

int main(int argc, char *argv[])
{
  cout<< whoAmI <<endl; //the global
  cout<< sde::whoAmI <<endl; //sde
  cout<< Val::whoAmI <<endl; //Val
  cout<< falsepride::whoAmI <<endl; //falsepride
  
  cout<<endl;

  wait_for_enter();
  return 0;
}

//---------------------auto generated------------------------------

void wait_for_enter()
{
  cout << "press <enter> to continue...";
  // Reset failstate, just in case.
  cin.clear();
  string line;
  getline( cin, line);
}
Basically, multiple coders can work on the same code, without clashing with eachothers variables and all. Just define your stuff in your very own namespace.

And now we're going to find out whyusing namespace std; is actually bad.
Try to compile the code as it is below:
Code:
#include <ios>
#include <string>

using namespace std;

string dec;

int main()
{
  dec = "december";

  return 0;
}
Aha! This doesn't compile.
"dec" is already defined in the std namespace. Houston, we have a problem. Do we want the coder to use a different variable name for the month december then? Naah. We gotta solve this:
Code:
#include <ios>
#include <string>

using std::string;

string dec;

int main()
{
  dec = "december";

  return 0;
}
If you want to use the "dec" indentifier as well, then use it like this: std::dec
Now you're using the <ios> dec as well.
However, one shouldn't redefine typically standard keywords like I do below:
bad code below
Code:
#include <ios>
#include <string>
#include <iostream>

using std::string;
using std::endl;

string dec;
//Bad bad bad boy.
int cout;

int main()
{
  dec = "december";
  cout = 1;
  
  //Argh...
  std::cout<< cout <<endl;

  return 0;
}
This should be enough brain teasing to get you started. Good luck!
__________________
Valmont is offline   Reply With Quote