473,785 Members | 2,468 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overloading operator []

I have not posted to comp.lang.c++ (or comp.lang.c++.m oderated)
before. In general when I have a C++ question I look for answers in
"The C++ Programming Language, Third Edition" by Stroustrup.
However, I've come upon a question that I can neither answer from
"The Book" or a Google search (so yes, at least I RTFBed). I'm
hoping that someone in this news group might know the answer.

Overloading the [] Operator

Say I want to develop a class that supports the overloaded []
operator and reads and writes the "int" type. I thought that the
way this was done was:

class MyClass
{
//...
// in theory, the RHS operator
const int operator[](const int i ) const;
// in theory, the LHS operator
int& operator[](const int i );
//...
}

Here RHS stands for right-hand-side, or an r-value and LHS stands
for left-hand-side, or an l-value.

MyClass foo;

int i = foo[j]; // RHS reference NOT!
foo[j] = i; // LHS reference

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS. I tried this with
Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
for Intel on freeBSD. Both compilers got the same results.

To put things in more concrete form, I've included a complete test
code below:

#include <stdio.h>

class overloaded
{
private:
int *pArray;

public:
overloaded( size_t size )
{
pArray = new int[ size ];
}

~overloaded()
{
delete [] pArray;
}

// in theory, the RHS operator
const int operator[](const int i ) const
{
printf("RHS a[%2d]\n", i );
return pArray[i];
}

// in theory, the LHS operator
int& operator[](const int i )
{
printf("LHS a[%2d]\n", i );
return pArray[i];
}
}; // overloaded
int
main()
{
const int len = 4;
overloaded a(len);
int b[len];

int i;

printf("initial izing array...\n");
for (i = 0; i < len; i++) {
a[i] = i + 1;
}

printf("reading values from array in an 'if' statement...\n" );
for (i = 0; i < len; i++) {
if (a[i] != i+1) {
printf("bad value");
break;
}
}

printf("reading values from an array in an assignment...\n ");
for (i = 0; i < len; i++) {
b[i] = a[i];
}

printf("express ion...\n");
int j = a[1] + a[2];
return 0;
}

When I compile and execute this code I get

initializing array...
LHS a[ 0]
LHS a[ 1]
LHS a[ 2]
LHS a[ 3]
reading values from array in an 'if' statement...
LHS a[ 0]
LHS a[ 1]
LHS a[ 2]
LHS a[ 3]
reading values from an array in an assignment...
LHS a[ 0]
LHS a[ 1]
LHS a[ 2]
LHS a[ 3]
expression...
LHS a[ 1]
LHS a[ 2]

I expected that the "initialization " would reference the LHS form of
the overloaded function. However, much to my surprise, the 'if'
statement and the value reads also referenced the LHS form of the
overloaded operator. I'm surprised at this, since as far as I can
tell, this way I've implemented the overloaded [] operators is
pretty much "text book" approach.

Is there a way to implement this class so that the RHS [] will be
called when it seems to be an r-value? That is

if (a[i] != i+1)
b[i] = a[i];
int j = a[1] + a[2];

In this example the difference is not critical, since the code gets
the expected results. However, proper invokation of the RHS and LHS
operators is important in the case of reference counted objects,
which is the appliction that originally motivated this question.

I'm working on a third version of a reference counted String class,
which can be found here:
http://www.bearcave.com/software/string/index.html. This class
suffers from a bug caused by the behavior of the [] operator
described above. In particular, it is making too many copies.

I have noted Stroustrup's solution using the Cref class (from 11.12
of "The Book"). However, in his code it appears that you might as
well omit the RHS version of the [] operator.

I'd be grateful for a version of the test code above that invokes
the RHS operator for what appear to be r-value references. Could
you please copy any postings on this to "iank at bearcave dot com".
Thank you for your help,

Ian
iank at bearcave dot com

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05
30 10452
> Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS. I tried this with
Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
for Intel on freeBSD. Both compilers got the same results.


What you need is to return a proxy class that overloads operator= and
operator int. Roughly:

class MyClass
{
public:
int operator[] (int i) const; // RHS
int_proxy operator[] (int i) { return int_proxy (p_ + i); }
private:
int *p_;
};

class int_proxy
{
public:
int_proxy& operator= (int val) { *r_ = val; }
operator int () const; // RHS
int_proxy (int* r): r_ (r) { }
private:
int *r_;
};

Essentially the int_proxy acts like a int&, but whatever special code
you would have put in the RHS function in the original, you put that
same code in the RHS function in the proxy. (Stylistically, you could
use templates and put int_proxy inside of MyClass.) I believe
std::vector<boo l> is specialized to do this.

Now when you call a [i], you get a temporary proxy. If there is an
access, then operator int gets called with your special RHS code; if
there is a mutate, then operator= gets called.

If it's all inline and optimizations are on, chances are the compiler
will optimize away the temporary int_proxy object. The only drawback I
can see is that the return type is no longer int&, which may crap out
code that expects it e.g. int& ri = a [i].

P.S. If you're irritated by having to repeat RHS code twice, either
cause the int_proxy version to call the MyClass version, or return a
const int_proxy from the MyClass RHS function.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #11
Rob

"(null)" <ia**@idiom.com > wrote in message news:1058054598 .920916@smirk.. .
[Snip]

class MyClass
{
//...
// in theory, the RHS operator
const int operator[](const int i ) const;
// in theory, the LHS operator
int& operator[](const int i );
//...
}

Here RHS stands for right-hand-side, or an r-value and LHS stands
for left-hand-side, or an l-value.

MyClass foo;

int i = foo[j]; // RHS reference NOT!
foo[j] = i; // LHS reference

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS. I tried this with
Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
for Intel on freeBSD. Both compilers got the same results.

[Snip]

This is actually the way it's supposed to be. foo is not a const object,
so when
there is a choice (as in this case) the non-const version of the operator
should
be invoked.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #12
"Francis Glassborow" <fr************ ****@ntlworld.c om> wrote in message
class hue{
public:
bool operator[](int bit)const {
if(bit <0 or bit >7) return false;
return bitset<8>(code_ )[bit];
}
class ref;
friend class hue::ref;
class ref{
public:
ref(hue & h, int n):h_(h),bit(n) {};
operator bool(){
if (bit <0 or bit >7) return false;
return bitset<8>(h_)[bit];
}
void operator=(bool val){
if(bit <0 or bit >7) return;
bitset<8> v(h_);
v[bit] = val;
h_ = (unsigned char)v.to_ulong ();
}
private:
hue & h_;
int bit;
};
ref operator[](int bit){return ref(*this, bit);}


How do you deal with the problem of replicating the interface of class bool
in class hue::ref? No problem with class bool as you only have to worry
about operator= as you did above (and I did in my example). But what about
other member functions like operator+=, memfun(), etc?

--
+++++++++++
Siemel Naran
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #13
> That is, why not simply write the following overloaded operator[]?

int& operator[](int index)


An int& is dumb, it cannot distinguish whether it is being written to
or read. A proxy object is smart, it knows when it is written (via
operator=) or read (via operator int), and can execute different code
as a result.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #14
In message <iG************ *********@bgtns c05-news.ops.worldn et.att.net>,
Siemel Naran <Si*********@RE MOVE.att.net> writes
How do you deal with the problem of replicating the interface of class bool
in class hue::ref? No problem with class bool as you only have to worry
about operator= as you did above (and I did in my example). But what about
other member functions like operator+=, memfun(), etc?


Sorry, I am totally confused. bool is a fundamental type and not a
class. Operator bool 'returns' a bool by value.

--
ACCU Spring Conference 2003 April 2-5
The Conference you should not have missed
ACCU Spring Conference 2004 Late April
Francis Glassborow ACCU

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #15
"Francis Glassborow" <fr************ ****@ntlworld.c om> wrote in message
Siemel Naran <Si*********@RE MOVE.att.net> writes

How do you deal with the problem of replicating the interface of class boolin class hue::ref? No problem with class bool as you only have to worry
about operator= as you did above (and I did in my example). But what aboutother member functions like operator+=, memfun(), etc?


Sorry, I am totally confused. bool is a fundamental type and not a
class. Operator bool 'returns' a bool by value.


Say you have a class Foo. The operator[] that is non-const returns a proxy.
There is a function operator const Foo&() const. Then there is a function
void operator=(const Foo&). What about other member functions of class Foo?
So that we can say

EnvelopeClass env;
env["abc"]; // returns EnvelopeClass:: reference, which is conceptually a
Foo&
env["abc"] = Foo(3); // ok
env["abc"].memfun(); // oops

For the last line to work, class EnvelopeClass:: reference should have a
member function memfun() because class Foo has such a function. Then we
have to duplicate the entire interface of class Foo inside Foo::reference.
Quite a nuisance.

--
+++++++++++
Siemel Naran
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #16
In message <6X************ *********@bgtns c04-news.ops.worldn et.att.net>,
Siemel Naran <Si*********@RE MOVE.att.net> writes
Say you have a class Foo. The operator[] that is non-const returns a proxy.
There is a function operator const Foo&() const. Then there is a function
void operator=(const Foo&). What about other member functions of class Foo?
So that we can say

EnvelopeClas s env;
env["abc"]; // returns EnvelopeClass:: reference, which is conceptually a
Foo&
env["abc"] = Foo(3); // ok
env["abc"].memfun(); // oops

For the last line to work, class EnvelopeClass:: reference should have a
member function memfun() because class Foo has such a function. Then we
have to duplicate the entire interface of class Foo inside Foo::reference.
Quite a nuisance.


No, you are making assumptions as to what the class designer should
expose. The point of using a proxy class is exactly that it give the
class designer control whilst the return of a reference abandons it. If
we write any function that returns a plain reference to private data we
have exposed that data and lost control of it. The main motive for
having private data is exactly to avoid such circumstances. If a member
function returns a plain reference we might as well make the data
public.
--
ACCU Spring Conference 2003 April 2-5
The Conference you should not have missed
ACCU Spring Conference 2004 Late April
Francis Glassborow ACCU

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #17
Francis Glassborow wrote:
...
No, you are making assumptions as to what the class designer should
expose. The point of using a proxy class is exactly that it give the
class designer control whilst the return of a reference abandons it.
If
we write any function that returns a plain reference to private data we
have exposed that data and lost control of it.
Not true. We gave user full control of the value, which doesn't
necessarily mean that we "lost" control of it in negative sense of the
word, since the object that returned the reference might not even care
about this control.
The main motive for
having private data is exactly to avoid such circumstances. If a member
function returns a plain reference we might as well make the data
public.
...


Not true.

There still is one (although thin) level of protection that is not
destroyed by returning a reference to private data. It doesn't expose
the actual location of the lvalue, i.e. it doesn't declare loud and
clear that the returned reference is bound to a subobject of the class.
Making a subobject 'public' immediately removes this last layer of
protection.

For example, making a subobject 'public' allows user to make assumptions
about the lifetime of subobject based on the lifetime of the entire
object. Accessor member function that returns a reference prevents user
to make such assumptions.

--
Best regards,
Andrey Tarasevich
Brainbench C and C++ Programming MVP

Jul 19 '05 #18
Francis Glassborow wrote:
...
No, you are making assumptions as to what the class designer should
expose. The point of using a proxy class is exactly that it give the
class designer control whilst the return of a reference abandons it.
If
we write any function that returns a plain reference to private data we
have exposed that data and lost control of it.
Not true. We gave user full control of the value, which doesn't
necessarily mean that we "lost" control of it in negative sense of the
word, since the object that returned the reference might not even care
about this control.
The main motive for
having private data is exactly to avoid such circumstances. If a member
function returns a plain reference we might as well make the data
public.
...


Not true.

There still is one (although thin) level of protection that is not
destroyed by returning a reference to private data. It doesn't expose
the actual location of the lvalue, i.e. it doesn't declare loud and
clear that the returned reference is bound to a subobject of the class.
Making a subobject 'public' immediately removes this last layer of
protection.

For example, making a subobject 'public' allows user to make assumptions
about the lifetime of subobject based on the lifetime of the entire
object. Accessor member function that returns a reference prevents user
to make such assumptions.

--
Best regards,
Andrey Tarasevich
Brainbench C and C++ Programming MVP
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #19
> EnvelopeClass env;
env["abc"]; // returns EnvelopeClass:: reference, which is conceptually a
Foo&
env["abc"] = Foo(3); // ok
env["abc"].memfun(); // oops

For the last line to work, class EnvelopeClass:: reference should have a
member function memfun() because class Foo has such a function. Then we
have to duplicate the entire interface of class Foo inside Foo::reference.
Quite a nuisance.


At the cost of some minor ickiness you could:
1. Make the proxy overload operator*, operator-> and operator->*
(can't remember whether you can overload operator.*). So you could do
something like env["abc"]->memfun ();
2. For consistency, you could have operator= take a T*.
3. Entirely different track: both the proxy and the object could
inherit from some base class, using the "curiously recursive" pattern
to avoid virtual functions.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
5247
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that discussions of new and delete is a pretty damn involved process but I'll try to stick to the main information I'm looking for currently. I've searched around for about the last too weeks and have read up on new and overloading it to some extent but...
16
3097
by: gorda | last post by:
Hello, I am playing around with operator overloading and inheritence, specifically overloading the + operator in the base class and its derived class. The structure is simple: the base class has two int memebers "dataA", "dataB". The derived class has an additional int member "dataC". I am simply trying to overload the + operator so that 'adding' two objects will sum up the corresponding int members.
2
2067
by: pmatos | last post by:
Hi all, I'm overloading operator<< for a lot of classes. The question is about style. I define in each class header the prototype of the overloading as a friend. Now, where should I define the overloading of operator<<. In the .cc of the respective class or in a file where I am overloading operator<< for all classes? Cheers,
5
2490
by: luca regini | last post by:
I have this code class M { ..... T operator()( size_t x, size_t y ) const { ... Operator overloading A ....} T& operator()( size_t x, size_t y )
2
2261
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It uses map<and heavy overloading. The problem is, the output file differs from input, and for the love of me I can't figure out why ;p #include <iostream> #include <fstream> #include <sstream>
5
3630
by: Jerry Fleming | last post by:
As I am newbie to C++, I am confused by the overloading issues. Everyone says that the four operators can only be overloaded with class member functions instead of global (friend) functions: (), , ->, =. I wonder why there is such a restriction. Some tutorials say that 'new' and 'delete' can only be overloaded with static member functions, others say that all overloading function should be non-static. Then what is the fact, and why? ...
3
3283
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj, obj2 ;
9
3515
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by allowing the assignment operator (=) to be overloaded. One particular use for this would be to implement "lazy evaluation". For example it would allow us to get rid of all the temporary arrays produced by NumPy. For example, consider the...
2
4442
by: Colonel | last post by:
It seems that the problems have something to do with the overloading of istream operator ">>", but I just can't find the exact problem. // the declaration friend std::istream & operator>(std::istream & in, const Complex & a); // the methods correspond to the friend std::istream & operator>(std::istream & in, const Complex & a) { std::cout << "real: ";
8
2976
by: Wayne Shu | last post by:
Hi everyone, I am reading B.S. 's TC++PL (special edition). When I read chapter 11 Operator Overloading, I have two questions. 1. In subsection 11.2.2 paragraph 1, B.S. wrote "In particular, operator =, operator, operator(), and operator-must be nonstatic member function; this ensures that their first operands will be lvalues". I know that these operators must be nonstatic member functions, but why this ensure their first operands will...
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9491
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10357
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10163
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10104
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.