TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: TIM HUTZLER
from: BLAKE GAFFNEY
date: 1998-04-09 21:14:00
subject: overloaded[][]

On the 01 Apr 98, Tim Hutzler performed the most audacious feat of 
simultaneous gibbering and moaning. It was generally directed at All
 TH> I want to overload the '[' to facillitate 2-dimentional arrays, ie.
 TH> thisVal = table[x][y];
 TH> Since 'table' is dynamically allocated, stactic subscripting does not
 TH> work here. Overloading a single subscript is easy, but two...???
 TH> Who knows how this can be done?
It can be done. The idiom for this is to return multiple class objects, using 
a private nested class. 
'table' should be of type class dynamic_2d. dynamic_2d::operator[]
constructs and returns an object of type class dynamic_2d::internal. 
dynamic_2d::internal::operator[] returns the correct value.
The complete (but untested) classes look a bit like this (Standard C++):
======= dynamic_2d.h =======
class dynamic_2d {
 class internal;
public:
 internal operator[](int);
};
class dynamic_2d::internal {
 int x;
public:
 internal(int);
 float operator[](int);
};
======= dynamic_2d.cc =======
#include 
#include "dynamic_2d.h"
internal dynamic_2d::operator[](int subscript)
{
 return internal(subscript);
}
float dynamic_2d::internal::operator[](int y)
{
 cout<<"I should return the value of subscript ",x,' ',y,'\n';
 return 123.456;
}
dynamic_2d::internal::internal(int x)
{
 this->x=x;
}
======= main.cc =======
#include "dynamic_2d.h"
main()
{
 dynamic_2d array;
 array[12][77];
 array[123][456];
}
Running this should produce the output:
I should return the value of subscript 12 77
I should return the value of subscript 123 456
Oh, this idiom can also be extended to create l-value sensitive classes. 
Handy if you want to make a class for disk-operations that need to know if 
they should read or write data.
Looks like *another* happy ending!
 offworld@bleach.demon.co.uk   >##<
... I am NOT Paranoid! And why are you always watching me??
 >> Tag-o-Miga 1.1a - Quoted 14% - 772 tags in Taglines.txt <<
--- Spot 1.3a #1508
---------------
* Origin: None (2:442/107.7)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.