Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!gem.mps.ohio-state.edu!tut.cis.ohio-state.edu!snorkelwacker!bloom-beacon!eru!luth!sunic!tut!tukki!sakkinen From: sakkinen@tukki.jyu.fi (Markku Sakkinen) Newsgroups: comp.lang.c++ Subject: Re: C++ 2.0 Question -- Whats wrong with this code ?? Message-ID: <1532@tukki.jyu.fi> Date: 18 Oct 89 07:20:50 GMT References: <981@odin.SGI.COM> Reply-To: sakkinen@jytko.jyu.fi (Markku Sakkinen) SAKKINEN@FINJYU.bitnet (alternative) Organization: University of Jyvaskyla, Finland Lines: 54 In article <981@odin.SGI.COM> mtoy@sgi.com (Michael Toy) writes: > >1 class Base { >2 public: >3 BaseClass(); >4 }; >5 extern TakesOne(BaseClass*&); >6 BaseClass::BaseClass() >7 { >8 BaseClass *equalsThis = this; >9 TakesOne(equalsThis); >10 TakesOne(this); >11 } > >This causes C++2.0 to tell me "reference to const object" on line 10 >Other than the workaround in lines 8&9, how would I write line >10 so that the compiler liked it? Clearly I am missing some >simple thing, it seems like this should work. According to the reference manual, 'this' is a _constant_ pointer (to the current class object) in Release 2.0, which it wasn't in previous releases. Thus you really need your workaround. As an alternative, if your function TakesOne will not modify its argument, I think you can declare extern TakesOne(BaseClass*const&); Then line 10 should be legal. By the way, I think this change in C++ 2.0 is very good for preventing some puzzling errors, even if some completely good code will also get bitten by the incompatibily between releases. In fact, let's take a look at a situation similar to your example: Some ordinary member function (not a constructor) calls TakesOne, and accesses some data member of the current object after that. It must then use the original value of 'this' - therefore the above workaround is necessary anyway. In older versions of C++, one can inadvertently get 'this' itself changed. The original example does concern a constructor, however. Assignment to 'this' in constructors and destructors for the purpose of programmer-controlled memory allocation and deallocation was a badly structured hack to start with. In Release 2.0 it has been replaced by the possibility to redefine the operators 'new' and 'delete', which is much better and cleaner. Moreover, I suspect that the older translators require an explicit assignment operation for 'this' within the constructor function itself in order to recognise the purpose; calling another function to do the trick would then not do (but I am not quite sure about this). Markku Sakkinen Department of Computer Science University of Jyvaskyla (a's with umlauts) Seminaarinkatu 15 SF-40100 Jyvaskyla (umlauts again) Finland