Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!usc!wuarchive!uunet!tdatirv!sarima From: sarima@tdatirv.UUCP (Stanley Friesen) Newsgroups: comp.lang.c++ Subject: Re: const Message-ID: <142@tdatirv.UUCP> Date: 5 Sep 90 15:59:11 GMT References: <10863@cadillac.CAD.MCC.COM> Reply-To: sarima@tdatirv.UUCP (Stanley Friesen) Organization: Teradata Corp., Irvine Lines: 40 In article <10863@cadillac.CAD.MCC.COM> vaughan@puma.cad.mcc.com (Paul Vaughan) writes: >Consider the following function >const char* substring(const char* string, const char* sub) >// substring searches for the first occurence of sub in string and >//returns a pointer to it or 0 if none is found. >{ ....} > >If I'm working on a const char* (and, therefore, don't plan on changing >any part of it) this works just fine. However, if I'm working on a >char* and was planning to change part of it and was using substring to >find that part, this will cause a problem because substring returns a >const. ... >I can't declare substring as >char* substring(const char* string, const char* sub) >because it is returning a pointer to part of the string that is passed >in. I would declare it > >char* substring(char* string, const char* sub) > >but then I can't use it to deal with const char*'s, and, of course, I can't >overload it based on the return type! But I believe you *can* overload it on the type of the first argument based on the presence/absence of 'const'. In other words, declare it *both* the first and the second way. This will then call either the const or non-const version depending on whether the first argument is a const string or not. --------------------------------- uunet!tdatirv!sarima (Stanley Friesen) -L -I -N -E - -C -N -T