Path: utzoo!mnetor!uunet!lll-winken!lll-lcc!ames!hao!oddjob!gargoyle!ihnp4!homxb!mtuxo!mtgzz!drutx!druhi!weh From: weh@druhi.ATT.COM (HopkinsBWE) Newsgroups: comp.lang.c++ Subject: Re: Now a bug (?) Message-ID: <2512@druhi.ATT.COM> Date: 29 Dec 87 17:39:48 GMT References: <370@targon.UUCP> Organization: AT&T, Denver, CO Lines: 64 Summary: formal argument needs to be a const & In article <370@targon.UUCP>, wim@targon.UUCP (Wim C. J. van Eerdt) writes: > #include > > class string { > //... > public: > > string(); > string( char* ); > string( string& ); > > friend ostream& operator<< ( ostream&, string& ); > > } ; > > const string text = "text"; > > void call() > { > > cout << text; // reference to a const object. > > } > > > A colleague typed the exhibited program and found an error on line > cout << text; > The message is correct: the 2nd argument of operator<< is a reference to a > string. So he changed the definition into > friend ostream& operator<< ( ostream&, string ); > Surprise, that did not work either: the constructor string( string& ) still > takes the reference of the constant object. Neither skipping the constructor > nor skipping the cont declaration is the answer, who knows the answer. Cfront won't allow one to pass a constant object by reference into a function unless the formal argument is also a constant. The error message from cfront (from a copy of the example in a file named ctest.c) is: CC ctest.c: "ctest.c", line 18: error: reference to const object 1 error Line 18 in my file is the ``cout << text; '' line. Thus, the function should have been declared as: friend ostream& operator<< ( ostream&, const string& ); Sure enough, cfront happily compiled it after the change. Since changes to parameters passed by reference change the actual argument, cfront cannot allow a constant to be passed as a non-constant reference. The solution of declaring the argument as simply a ``string'' fails because that requires the creation of a new copy of ``string'' from an existing string, meaning that string::string(string&) must be called. Since it declares the argument as a nonconstant reference, it suffers from the same problem as with operator>> (the same error message from cfront). The solution is similar: declare the constructor as ``string(const string&);''. This solution, too, has been confirmed by cfront. Bill Hopkins AT&T ihnp4!druhi!weh