473,698 Members | 2,432 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 17945
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
3087
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
3579
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
1784
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
3275
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
3613
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
1792
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
2971
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
1948
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
8678
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
8609
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
9166
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
9030
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...
0
7737
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
5861
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();...
0
4371
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4621
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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

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.