Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!husc6!think!ames!pasteur!ucbvax!decwrl!hplabs!sdcrdcf!trwrb!cadovax!gryphon!sarima From: sarima@gryphon.CTS.COM (Stan Friesen) Newsgroups: comp.lang.c++ Subject: Re: overloading array indexing Keywords: [] bugs? array indexing Message-ID: <4023@gryphon.CTS.COM> Date: 15 May 88 14:10:30 GMT References: <451@ethz.UUCP> Reply-To: sarima@gryphon.CTS.COM (Stan Friesen) Organization: Trailing Edge Technology, Redondo Beach, CA Lines: 35 In article <451@ethz.UUCP> peter@ethz.UUCP (Peter Beadle) writes: > >I have been trying to overload the array indexing operation as part of >a simulator I am writing. ... > >The translator produces a _tiny__vec function when I don't inline the >overload. This function contains the correct code but it never gets >called in main. ... > >/* test program */ >#include >class tiny{ > int v; >public: > tiny() {v=0;} > void operator[](int i) { cerr << "in overloaded []\n"; } >}; > >main() { > tiny fred[5]; > > fred[2]; >} > AH, I see the problem. The declaration creates a REAL array of 5 "tiny" objects called fred. Thus the expression "fred[2]" later indexes into this array, generating a reference to a tiny object . You would have to say "fred[2][2]" to get tiny::operator[], since that is only applied to a "tiny" object, not an array of "tiny" objects. Look on page 182 of Stroustrup's book and note that he declaes an instance of his "assoc" class, which has a [] operator, as "assoc vec(512)" not "assoc vec[512]". -- Sarima Cardolandion sarima@gryphon.CTS.COM aka Stanley Friesen rutgers!marque!gryphon!sarima Sherman Oaks, CA