Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

noob question c++

Name: Anonymous 2009-07-12 13:15

Why doesn't this work?

#include <iostream>
using namespace std;
int main(int argc,char** argv){
   string name;
   cout<<"What is your name?"<<endl;
   cin>>name;
   if(name=="Anonymous")
   cout<<"Aw don't be shy..."<<endl;
   else
   cout<<"Hello "<<name<<"!"<<endl
   return 0;
}

Name: Anonymous 2009-07-12 21:03

>>13
It makes intuitive sense to compare objects with ==; you're testing whether they're the same instance.
Even that isn't true, though. Conceptually, == tests object equality, because it works that way for primitives. This is in fact especially obvious for the primitives, which is why Sun tried to fix it by making the == operator compare by value for the primitive wrapper classes (except where they didn't), but it's conceptually the same for any kind of object. Having it test reference equality is just leaky abstraction.

Testing for object equality is much more common than testing for reference equality anyway, because most of the time you're comparing objects is when you're sorting them or when you're trying to match strings, so even without the conceptual break there's a good pragmatic argument for having == call .equals() and just having some immutable magic instance variable in the object representing its identity so people can compare reference equality using that.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List