473,748 Members | 8,779 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(vo id) {
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 1249

Kush wrote in message
<11************ **********@m7g2 000cwm.googlegr oups.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(vo id) {
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
misconceptio n?
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_ran ge();} // 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(vo id) {
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_ran ge("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(vo id) {
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
3692
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? Right now I just use typedef vector<double>TS; Is that enough? I feel that I am not taking advantage of the C++
11
1745
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
5246
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...
7
1831
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 xydata with operator- overloaded: class xydata { public:
110
4506
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
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
2257
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>
3
3279
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 ;
2
4438
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
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...
0
8989
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
8828
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
9537
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
9367
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
9319
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,...
1
6795
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
6073
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
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
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.