473,326 Members | 2,061 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Question about overloading the [ ] operator

Hello All,

Once again another question. :)

This time I would like to understand why one needs to overload the [ ]
operator to access objects in array format?

Example code:

class A {
{ };

class B {
private:
A array[10];
A* pA = array;

public:
A& operator [ ] (int i) { return pA[i]; } //Line 1:

void do_something(void) {
A a;
a = pA[2]; } //Line 2
};

Why do I need Line 1? Since pA is a pointer of type A, can I not
directly access "array members" using simple pointer arithmetic?

i.e. without declaring Line 1, use Line 2
or equivalently use the below statement to replace Line 2
a = *(pA + 2);

I'm sure I'm missing something. Can someone please point out my
misconception?

Thanks again in advance!

Kush

Nov 13 '06 #1
3 1229

Kush wrote in message
<11**********************@m7g2000cwm.googlegroups. com>...
>Hello All,

Once again another question. :)

This time I would like to understand why one needs to overload the [ ]
operator to access objects in array format?

Example code:

class A { };

class B {
private:
A array[10];
A* pA = array;
public:
A& operator [ ] (int i) { return pA[i]; } //Line 1:

void do_something(void) {
A a;
a = pA[2]; } //Line 2
};

Why do I need Line 1? Since pA is a pointer of type A, can I not
directly access "array members" using simple pointer arithmetic?

i.e. without declaring Line 1, use Line 2
or equivalently use the below statement to replace Line 2
a = *(pA + 2);

I'm sure I'm missing something. Can someone please point out my
misconception?
Thanks again in advance!
Kush
One good reason might be: to check the index for range.

A& operator [ ] ( int i ) {
if( i < 0 || i 9 ){ throw std::out_of_range();} // or 'assert', or ?
return pA[ i ];
} //Line 1:

--
Bob R
POVrookie
Nov 13 '06 #2

Kush wrote:
Hello All,

Once again another question. :)

This time I would like to understand why one needs to overload the [ ]
operator to access objects in array format?

Example code:

class A {
{ };

class B {
private:
A array[10];
A* pA = array;

public:
A& operator [ ] (int i) { return pA[i]; } //Line 1:

void do_something(void) {
A a;
a = pA[2]; } //Line 2
};

Why do I need Line 1? Since pA is a pointer of type A, can I not
directly access "array members" using simple pointer arithmetic?
Line 1 is there to access the array from the outside world. You don't
need the pointer pA at all.
array already decays to a pointer anyways.
>
i.e. without declaring Line 1, use Line 2
or equivalently use the below statement to replace Line 2
a = *(pA + 2);
There is no need:
A a = array[2];
will do

Try something like this, although a std::vector would be more usefull:

#include <iostream>
#include <stdexcept>

class A { };

template< typename T , const size_t Size >
class B
{
T array[Size];
public:
A& operator [ ] (size_t i)
{
if(i < 0 || i Size - 1)
throw std::out_of_range("array out of bounds");
return array[i];
}
void do_something()
{
T a;
a = array[2];
}
};

int main()
{
try {
B< A, 10 b;
// A a = b[11]; // throws
b.do_something();
}
catch( const std::exception& r_e )
{
std::cerr << "Error: ";
std::cerr << r_e.what() << std::endl;
}
}

___
Note that a std::vector has an at(...) member function that does the
range_check for you.
Its so much easier to do the above with a vector.

#include <iostream>
#include <vector>
#include <stdexcept>

template< typename T >
class B
{
std::vector< T vt;
public:
B(size_t size, const T& t = T())
: vt(size, t) { } // ctor
T& operator[](size_t i)
{
return vt.at(i);
}
void do_something()
{
vt.at(2) = 33.3;
}
};

int main()
{
try {
B< double b( 5, 11.1 );
// A a = b[11]; // throws
b.do_something();
for(size_t i = 0; i < 10; ++i)
{
std::cout << "b[" << i << "] = ";
std::cout << b[i] << std::endl;
}
}
catch( const std::exception& r_e )
{
std::cerr << "Error: ";
std::cerr << r_e.what() << std::endl;
}
}

/*
b[0] = 11.1
b[1] = 11.1
b[2] = 33.3
b[3] = 11.1
b[4] = 11.1
*/

Nov 13 '06 #3
Kush:
This time I would like to understand why one needs to overload the [ ]
operator to access objects in array format?

The same reason why you have to eat with a spoon: You don't, but everyone's
doing it.

Example code:

class A {
{ };

class B {
private:
A array[10];
A* pA = array;

public:
A& operator [ ] (int i) { return pA[i]; } //Line 1:

void do_something(void) {
A a;
a = pA[2]; } //Line 2
};

Why do I need Line 1? Since pA is a pointer of type A, can I not
directly access "array members" using simple pointer arithmetic?

Within the class, yes you can. The operator[] you have provided is so that
outside of the class, people can do:

B obj;

obj[5] = ... ;

i.e. without declaring Line 1, use Line 2
or equivalently use the below statement to replace Line 2
a = *(pA + 2);

Both in C and in C++, the following:

arr[i]

is equivalent to: *(arr+i)

which is equivalent to: *(i+arr)

which is equivalent to: i[arr]

--

Frederick Gotham
Nov 13 '06 #4

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

Similar topics

7
by: Jessica | last post by:
Hi, I have a design question. I am making a time series analysis tool. Since I already use STL vector to represent time series, is there a need to implement a class for the time series object? ...
11
by: billnospam | last post by:
Is it possible to overload operators in vb.net? Is it possible to do programmer defined boxing on byvalue variables in vb.net?
5
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...
7
by: Eckhard Lehmann | last post by:
Hi, I try to recall some C++ currently. Therefore I read the "Standard C++ Bible" by C. Walnum, A. Stevens and - of course there are chapters about operator overloading. Now I have a class...
110
by: Vijay Kumar R Zanvar | last post by:
Hi, Which section of C99 says that return value of malloc(3) should not be casted? Thanks. -- Vijay Kumar R Zanvar My Home Page - http://www.geocities.com/vijoeyz/
5
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
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...
3
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,...
2
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 &...
8
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,...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.