473,396 Members | 2,004 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,396 software developers and data experts.

Subscript operator overloading

6
Hi all

This seems to me a peculiar problem, but confounding nonetheless...

The problem seems to be that an overloaded subscript operator isn't being called unless it is called explicitly

Expand|Select|Wrap|Line Numbers
  1. struct myStruct
  2. {
  3.     myStruct& operator[] (int index)
  4.     {    
  5.         return *(this + index);
  6.     }
  7.  
  8.     bool val1;
  9.     int val2;
  10.     float val3;
  11.     double val4;
  12. };
  13.  
  14. int main()
  15. {
  16. myStruct *s = new myStruct[5];
  17. s[0].val1 = true;//works, but does not call the overloaded operator
  18. s->operator[](0).val1 = 1;//calls the overloaded operator - also works
  19.  
  20. ...
  21. }
  22.  
I can't find anything on the Internet or any textbooks about this. Any clues as to why this doesn't work would be appreciated.

Thanks, Greg
Apr 3 '07 #1
4 5182
Ganon11
3,652 Expert 2GB
Hi all

This seems to me a peculiar problem, but confounding nonetheless...

The problem seems to be that an overloaded subscript operator isn't being called unless it is called explicitly

Expand|Select|Wrap|Line Numbers
  1. struct myStruct
  2. {
  3.     myStruct& operator[] (int index)
  4.     {    
  5.         return *(this + index);
  6.     }
  7.  
  8.     bool val1;
  9.     int val2;
  10.     float val3;
  11.     double val4;
  12. };
  13.  
  14. int main()
  15. {
  16. myStruct *s = new myStruct[5];
  17. s[0].val1 = true;//works, but does not call the overloaded operator
  18. s->operator[](0).val1 = 1;//calls the overloaded operator - also works
  19.  
  20. ...
  21. }
  22.  
I can't find anything on the Internet or any textbooks about this. Any clues as to why this doesn't work would be appreciated.

Thanks, Greg
I'm not completely sure about this, but allow me to give you an educated guess:

In your first example s[0].val1 = true; you are using the subscript operator on the pointer. This will return the first myStruct in the array - you can then access val1 correctly. However, the subscript operator is called on the pointer, not the struct.

In your second example s->operator[](0).val1 = 1; the -> is evaluated on the pointer first, giving you the myStruct at s (Since s is a pointer to an array, it will return the first element of the array). Then you call the subscript function explicitly.

You may be able to use the overloaded function like this:

Expand|Select|Wrap|Line Numbers
  1. myStruct *s = new myStruct[5];
  2. s[0][0].val1 = true;
As an aside, what are you trying to accomplish by overloading the [] operator? It looks like you are treating the object as an array, but it will actually give you the address in memory index slots in front of the object, which will be pointing to random, garbage memory.
Apr 3 '07 #2
JosAH
11,448 Expert 8TB
You defined an overloaded operator on a type T, not on a type T* (which is
impossible btw). Doing a *(this+index) is extremely dangerous because it
assumes that all your type Ts are stored consecutively in memory; and that's
not what the operator[](int) is supposed to do when overloaded, i.e. the non-
overloaded version can do that too; it doesn't need overloading for that.

kind regards,

Jos
Apr 3 '07 #3
gvr123
6
I'm not completely sure about this, but allow me to give you an educated guess:

In your first example s[0].val1 = true; you are using the subscript operator on the pointer. This will return the first myStruct in the array - you can then access val1 correctly. However, the subscript operator is called on the pointer, not the struct.

In your second example s->operator[](0).val1 = 1; the -> is evaluated on the pointer first, giving you the myStruct at s (Since s is a pointer to an array, it will return the first element of the array). Then you call the subscript function explicitly.

You may be able to use the overloaded function like this:

Expand|Select|Wrap|Line Numbers
  1. myStruct *s = new myStruct[5];
  2. s[0][0].val1 = true;
As an aside, what are you trying to accomplish by overloading the [] operator? It looks like you are treating the object as an array, but it will actually give you the address in memory index slots in front of the object, which will be pointing to random, garbage memory.
Hi

Here's a more compete example of what I'm trying to do:

Effectively I'm trying to implement some bounds checking on the array. I wanted to leave the pointer to the array of Struct2 public (for various reasons) but still wanted to provide some additional safety. (The pointer is const in the actual implementation)

Expand|Select|Wrap|Line Numbers
  1. struct myStruct2
  2. {
  3.     myStruct2() { memset((void*)this, 0, sizeof(myStruct2)); }
  4.     ~myStruct2(){}
  5.     myStruct2& operator[] (int index)
  6.     {    
  7.         return *(this + index);//increment this by index
  8.     }
  9.  
  10.     bool val1;
  11.     int val2;
  12.     float val3;
  13.     double val4;
  14. };
  15.  
  16. struct myStruct
  17. {
  18.     myStruct() : number(0), pStruct(NULL)
  19.     {
  20.     }
  21.  
  22.     ~myStruct()
  23.     {
  24.         if(pStruct) delete [] pStruct;
  25.         pStruct = NULL;
  26.     }
  27.  
  28.     void alloc(int num)
  29.     {
  30.         pStruct = new myStruct2[num];
  31.         if(pStruct) number = num;
  32.         else number = 0;
  33.     }
  34.  
  35.     int number;
  36.     myStruct2* pStruct;
  37. };
  38.  
  39. int main()
  40. {
  41.     myStruct s;
  42.  
  43.     s.alloc(5);
  44.  
  45.     s.pStruct[4].val1 = true;
  46.     s.pStruct[4].val2 = 1;
  47.     s.pStruct[4].val3 = 2.2F;
  48.     s.pStruct[4].val4 = 3.33;
  49.  
  50.     myStruct2 s3 = s.pStruct[4];
  51.  
  52.     myStruct2 s4 = s.pStruct->operator [](4);
  53.  
  54.  
  55.     return 0;
  56. }
  57.  
The deferencing seems to work fine - s3 and s4 are identical - but I get what you mean by operating on the struct rather than the pointer.

So what i really want to know is is it possible to force the array subscript to use the struct operator[]?

Thanks
Apr 3 '07 #4
JosAH
11,448 Expert 8TB
Hi
So what i really want to know is is it possible to force the array subscript to use the struct operator[]?

Thanks
You basically want to do the same as a vector<T>; the vector takes care of the
overloaded operator[] which is the only way to do it because you can't overload
anything on a primitive type such as a pointer to T (or an array of T).

kind regards,

Jos
Apr 3 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

15
by: Steve | last post by:
Hi, I hope someone can help. I have a class called cField, and another class called cFieldList. cFieldList contains a std::vector of cFields called myvec I've overloaded the subscript...
5
by: Steve | last post by:
Hi, I have a class called cList as so: template<class T> class cList { // base class for Lists private: protected: vector<T> tListOf; // field list container public: void Add(const T& t)...
10
by: olson_ord | last post by:
Hi, I am not exactly new to C++, but I have never done operator overloading before. I have some old code that tries to implement a Shift Register - but I cannot seem to get it to work. Here's a...
51
by: Pedro Graca | last post by:
I run into a strange warning (for me) today (I was trying to improve the score of the UVA #10018 Programming Challenge). $ gcc -W -Wall -std=c89 -pedantic -O2 10018-clc.c -o 10018-clc...
3
by: mural | last post by:
hai all how can i overload the subscript with more than one dimension like .. if possible please give an example.. thank you
6
by: josh | last post by:
Hi I've a dubt! when we have overloaded functions the compiler chooses the right being based on the argument lists...but when we have two subscript overloaded functions it resolves them being...
5
by: raan | last post by:
What I am trying to achieve here is depicted in the small program below. // Wrapit.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <map> #include...
5
by: sendos | last post by:
Consider the following sample code #include <iostream> using namespace std; class A { public: int x; A(int n = 0) : x(n) {};
19
by: C++Liliput | last post by:
I have a custom String class that contains an embedded char* member. The copy constructor, assignment operator etc. are all correctly defined. I need to create a map of my string (say a class...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...

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.