473,804 Members | 3,174 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Subscript operator overloading

6 New Member
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 5209
Ganon11
3,652 Recognized Expert Specialist
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 Recognized Expert MVP
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 New Member
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 Recognized Expert MVP
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
2170
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 operator for cFieldList as so: cField& operator(int pos) { return myvec; }
5
1889
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) {tListOf.push_back(t);} // add new object to list unsigned int Count() { return tListOf.size(); } // number of list items
10
3154
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 simpler version of it. -------------------- main.cpp--------------------------- # include <iostream>
51
23751
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 10018-clc.c: In function `main': 10018-clc.c:22: warning: array subscript has type `char' I don't like warnings ... or casts.
3
413
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
2735
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 based on the const type. Infact if I use the Array on the left side i.e like a1 = 111 then it uses the first while if I use cout << a1 it uses the second... why????
5
2466
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 <list>
5
5941
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
3533
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 called MyString) and an integer i.e. std::map<MyString, int>. Whenever I insert the elements in the map using the subscript operator, I noticed that the copy constructor for MyString is invoked more number of times than if I do it using the insert()...
0
9706
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
9579
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
10577
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
10332
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
6853
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
5521
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
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4299
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
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.