473,734 Members | 2,824 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

index operator[] overloading

Can anyone explain how this works. How may I implement this?

I want to be able to use the operator on both lhs and rhs of assignment
statements. The rhs is a no-brainer (at least I think I got it right):

class MyArray
{
public:
MyArray(const size_t size):m_size(si ze){ arr_ = new double[size]; }
~MyArray(){ if (arr_) delete[] arr_ ;}

double operator[](const size_t idx)
{ if (idx < m_size)
return arr_[idx];
throw std::exception
}

private:
MyArray(const MyArray&);
operator= (const MyArray&);

double *arr_ ;
size_t m_size ;
}
I read somewhere that the type returned from the [] operator must be a
reference, but I did not quite follow the reasoning/logic - anyone care
to explain ?
May 29 '07 #1
15 17953
Bart Simpson wrote:
>
I read somewhere that the type returned from the [] operator must be a
reference, but I did not quite follow the reasoning/logic - anyone care
to explain ?
A reference is a variable that relates to another variable. for example

int x = 0;
int& y = x;
y = 1;

at the end, x will have a value of 1, because y refers to the same
memory location as x, so it's bind to the x value until the end of its
scope (that hopefully is before or at the same time as the x one :)

In your case it's exactly the same: if you return a reference, you are
returning a (temporary) variable that refers to the address of the
element that you want to modify. So, if you assign a value to this
variable (that would be prohibited if it wasn't a reference, because is
a temporary), the value will be written in the memory location of your
array element.

that's it!

Regards,

Zeppe
May 29 '07 #2
Thanks Zeppe that clarifies that.

So to implement it one has to implement BOTH of these?

myType operator[](const size_t) const;
myType& operator[](const size_t);
May 29 '07 #3
Bart Simpson wrote:
Thanks Zeppe that clarifies that.

So to implement it one has to implement BOTH of these?

myType operator[](const size_t) const;
myType& operator[](const size_t);
exactly, and the compiler will chose the proper one based on the
"const". Another hint: the method

myType operator[](const size_t) const;

makes a copy of the element that it returns, which can be undesirable if
the objects myType are big. So, it usually common to do

const myType& operator[](const size_t) const;
myType& operator[](const size_t);

if you return a const reference, you can't use it in the left side of
the assignment, and you avoid the copy on the return.

Regards,

Zeppe
May 29 '07 #4


Zeppe wrote:
Bart Simpson wrote:
>Thanks Zeppe that clarifies that.

So to implement it one has to implement BOTH of these?

myType operator[](const size_t) const;
myType& operator[](const size_t);


exactly, and the compiler will chose the proper one based on the
"const". Another hint: the method

myType operator[](const size_t) const;

makes a copy of the element that it returns, which can be undesirable if
the objects myType are big. So, it usually common to do

const myType& operator[](const size_t) const;
myType& operator[](const size_t);

if you return a const reference, you can't use it in the left side of
the assignment, and you avoid the copy on the return.

Regards,

Zeppe
Thanks!
May 29 '07 #5
On May 29, 7:30 pm, Zeppe
<zep_p@.remove. all.this.long.c omment.yahoo.it wrote:
Bart Simpson wrote:
Thanks Zeppe that clarifies that.
So to implement it one has to implement BOTH of these?
myTypeoperator[](constsize_t)co nst;
myType&operator[](constsize_t);

exactly, and the compiler will chose the proper one based on the
"const". Another hint: the method
To the much of my surprise, I tried this and the non-constant version
is always called. Here is the code:

#include <iostream>

class MyArray
{
public:
MyArray(const size_t size) : m_size(size) {
arr_ = new double[size];
}

~MyArray() {
if (arr_) delete[] arr_ ;
}

double& operator[](const size_t idx)
{
std::cout << "LHS" << std::endl;
return arr_[idx];
}

const double& operator[](const size_t idx) const
{
std::cout << "RHS" << std::endl;
return arr_[idx];
}

double *arr_;
size_t m_size;
};

int main(int argc, char** argv) {
MyArray a(3);
a[0] = 8.0;
std::cout << a[0] << std::endl;
return 0;
}

The output in both cases is "LHS". What's wrong?

-Mustafa

May 29 '07 #6
Project X wrote:
On May 29, 7:30 pm, Zeppe
<zep_p@.remove. all.this.long.c omment.yahoo.it wrote:
>Bart Simpson wrote:
>>Thanks Zeppe that clarifies that.
>>So to implement it one has to implement BOTH of these?
>>myTypeoperato r[](constsize_t)co nst;
myType&operat or[](constsize_t);

exactly, and the compiler will chose the proper one based on the
"const". Another hint: the method

To the much of my surprise, I tried this and the non-constant version
is always called. Here is the code:

#include <iostream>

class MyArray
{
public:
MyArray(const size_t size) : m_size(size) {
arr_ = new double[size];
}

~MyArray() {
if (arr_) delete[] arr_ ;
}

double& operator[](const size_t idx)
{
std::cout << "LHS" << std::endl;
return arr_[idx];
}

const double& operator[](const size_t idx) const
{
std::cout << "RHS" << std::endl;
return arr_[idx];
}

double *arr_;
size_t m_size;
};

int main(int argc, char** argv) {
MyArray a(3);
a[0] = 8.0;
std::cout << a[0] << std::endl;
return 0;
}

The output in both cases is "LHS". What's wrong?
Nothing. 'a' is declared non-const. Why would a const function
be called when non-const is available?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 29 '07 #7
On 29 Maj, 21:03, Project X <elsheik...@gma il.comwrote:
On May 29, 7:30 pm, Zeppe

<zep_p@.remove. all.this.long.c omment.yahoo.it wrote:
Bart Simpson wrote:
Thanks Zeppe that clarifies that.
So to implement it one has to implement BOTH of these?
>myTypeoperat or[](constsize_t)co nst;
myType&operator[](constsize_t);
exactly, and the compiler will chose the proper one based on the
"const". Another hint: the method

To the much of my surprise, I tried this and the non-constant version
is always called. Here is the code:

#include <iostream>

class MyArray
{
public:
MyArray(const size_t size) : m_size(size) {
arr_ = new double[size];
}

~MyArray() {
if (arr_) delete[] arr_ ;
}

double& operator[](const size_t idx)
{
std::cout << "LHS" << std::endl;
return arr_[idx];
}

const double& operator[](const size_t idx) const
{
std::cout << "RHS" << std::endl;
return arr_[idx];
}

double *arr_;
size_t m_size;

};

int main(int argc, char** argv) {
MyArray a(3);
a[0] = 8.0;
std::cout << a[0] << std::endl;
return 0;

}

The output in both cases is "LHS". What's wrong?
Your program works fine. When the compiler chooses between operator[]
(const size_t idx) and operator[](const size_t idx) const, it makes
its determination based on whether the object in question is const or
not. Since your "a" is non-const, it will always choose the non-const
operator. Try e.g. adding this function and call it:

void f_const(MyArray const& a)
{
a[0];
}

then compare it with
void f_non_const(MyA rray& a)
{
a[0];
}

/Peter

May 29 '07 #8
In article <NM************ *********@bt.co m>, 12**********@te rrace.com
says...
Thanks Zeppe that clarifies that.

So to implement it one has to implement BOTH of these?

myType operator[](const size_t) const;
myType& operator[](const size_t);
You probably need a Proxy. See _More Effective C++_, Item 30.

--
Later,
Jerry.

The universe is a figment of its own imagination.
May 30 '07 #9
On Wed, 30 May 2007 06:51:09 -0600, Jerry Coffin wrote:
In article <NM************ *********@bt.co m>, 12**********@te rrace.com
says...
>Thanks Zeppe that clarifies that.

So to implement it one has to implement BOTH of these?

myType operator[](const size_t) const; myType& operator[](const
size_t);

You probably need a Proxy.
Why?
See _More Effective C++_, Item 30.
Um... not everyone has that book...

--
Lionel B
May 30 '07 #10

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

Similar topics

16
3090
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.
51
3589
by: Jojo | last post by:
Is there any way to get to the left-hand side of an operator? Consider the following (this is not meant to be perfect code, just an example of the problem): class Matrix { public: int data; Matrix() {}
13
1786
by: Jon Cosby | last post by:
VB .Net does support operator overloading, doesn't it? It seems like this should overload binary addition, but VB doesn't recognize "Operator" Public Shared Operator +(ByVal c1 as cnum, ByVal c2 as cnum) as cnum ' End of statement expected End Operator
2
2504
by: vivekian | last post by:
Have a pointer to an object of class type task task * A ; Now this object takes operator overloading like A<<2 ; which assigns the number 2 to one of the members of the object A.
3
3278
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 ;
22
3619
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float v);
2
1793
by: rn5a | last post by:
I use VB.NET to create ASP.NET apps. If I am not wrong, there is something called method overloading in VB.NET (like in C#) which is one of the features in OOP (polymorphism) but does VB.NET also include operator overloading like C# does? Ron
8
2974
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...
4
1950
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
Operator overloads are just like any other member function, you can make them do whatever you want. However, of course, we might expect them to behave in a certain way. The ++ operator should perform some sort of increment, the / operator should do something along the lines of division. Do you think it would have been worthwhile for the C++ Standard to "codify" this expected use of operator overloads? I'll be specific: Let's say you...
0
8946
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
8776
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
9449
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
9310
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
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.