473,327 Members | 1,919 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,327 software developers and data experts.

overloading [] operator

25
I am trying to overload [] operator like this.

char* myclass::operator[](char* str)
{
....
}

Basically I should be able to handle these cases

char* c1=myclass["test"];

char* c2="test2";
myclass["test']=c2;

So, myclass["test"] can appear either in rhs or lhs of an expression. In my operator[] function which has to handle these cases differently, how will I differentiate it?
Oct 19 '06 #1
11 1894
Banfa
9,065 Expert Mod 8TB
So, myclass["test"] can appear either in rhs or lhs of an expression. In my operator[] function which has to handle these cases differently, how will I differentiate it?
You can't.

operator[] should return a reference to the data to be written, if you are trying to create an array of strings indexed by strings you have chosen the wrong type the the return of operator[], try

string &myClass::operator[](const char* str)
{
}
Oct 19 '06 #2
guest
25
You can't.

operator[] should return a reference to the data to be written, if you are trying to create an array of strings indexed by strings you have chosen the wrong type the the return of operator[], try

string &myClass::operator[](const char* str)
{
}
Thanks for the correction. And your guess is correct. I am trying to create an array of strings indexed by strings. My problem is that I will create a place holder for the strings only in case of

myClass[s1]=s2; //creates memory for s1 and s2

and not in case of

s3=myClass[s1]; //doesn't create any thing. Just returns reference to indexed string

So the operator should behave differently in different cases. Is this possible?
Oct 19 '06 #3
Banfa
9,065 Expert Mod 8TB
myClass[s1]=s2; //creates memory for s1 and s2

and not in case of

s3=myClass[s1]; //doesn't create any thing. Just returns reference to indexed string

So the operator should behave differently in different cases. Is this possible?
In the second case you will be able to tell because when you look you look the index s1 in whatever method you are using for storage it will already exist. So the operator does this

Expand|Select|Wrap|Line Numbers
  1. LOOK UP INDEX
  2.  
  3. IF IT EXISTS
  4.     RETURN REFERENCE TO EXISTING MEMORY
  5. ELSE
  6.     CREATE NEW MEMORY
  7.     ASSOCIATE MEMORY WITH INDEX
  8.     RETURN REFERENCE TO NEW MEMORY
  9. ENDIF
  10.  
It does not need to know the context in which is is called.


You know you could get something extremely similar from

map<string, string>
Oct 19 '06 #4
dtimes6
73
It seems u need something like this:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. class CharPtr {
  5. private:
  6.     char* ptr;
  7.  
  8. public:
  9.     CharPtr& operator = (char* other) {
  10.         if(other== ptr)
  11.             return *this;
  12.         if(ptr)
  13.             delete [] ptr;
  14.         unsigned length = strlen( other);
  15.         ptr = new char[length];
  16.         memcpy(ptr,other,length);
  17.         return *this;
  18.     }
  19.     CharPtr(char* other) {
  20.         unsigned length = strlen( other);
  21.         ptr = new char[length];
  22.         memcpy(ptr,other,length);
  23.     }
  24.     CharPtr( const CharPtr& other) {
  25.         unsigned length = strlen( other.ptr);
  26.         ptr = new char[length];
  27.         memcpy(ptr,other.ptr,length);
  28.     }
  29.     CharPtr& operator=(const CharPtr& other) {
  30.         if(other.ptr== ptr)
  31.             return *this;
  32.         if(ptr)
  33.             delete [] ptr;
  34.         unsigned length = strlen( other.ptr);
  35.         ptr = new char[length];
  36.         memcpy(ptr,other.ptr,length);
  37.         return *this;
  38.     }
  39.     ~CharPtr() { if(ptr) delete [] ptr; }
  40.     CharPtr() :ptr(NULL){}
  41.     operator char* () {
  42.         return ptr;
  43.     }
  44. };
  45.  
  46. class T {
  47. private:
  48.     CharPtr a;
  49. public:
  50.     CharPtr& operator[]( const CharPtr& key) {
  51.         return a;
  52.     }
  53. };
  54.  
  55. int main()
  56. {
  57.     T a;
  58.     a["text"] = "putin";
  59.     printf("%s", (char*)a["text"]);
  60.     return 0;
  61. }
  62.  
Oct 19 '06 #5
guest
25
Thanks for the code, but it does not address multiple key value issue. For ex, if you changed main() like this,

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     T a;
  4.     a["text"] = "putin";
  5.     a["text2"] = "putin2";
  6.     printf("%s", (char*)a["text"]);
  7.     return 0;
  8. }
  9.  
Still it will output putin2. In other words, it always has placeholder for the latest string assigned. Key is just discarded and has no significance at all.

In the algorithm

Expand|Select|Wrap|Line Numbers
  1. LOOK UP INDEX
  2.  
  3. IF IT EXISTS
  4.     RETURN REFERENCE TO EXISTING MEMORY
  5. ELSE
  6.     CREATE NEW MEMORY
  7.     ASSOCIATE MEMORY WITH INDEX
  8.     RETURN REFERENCE TO NEW MEMORY
  9. ENDIF
  10.  
there is a flaw. If the index does not exist, it creates memory associated to that index. But if it is an rvalue (like in s2=myclass[s1]; ) and it does not exist, it has to just return null. Memory should not be created (and wasted).
Oct 19 '06 #6
Banfa
9,065 Expert Mod 8TB
there is a flaw. If the index does not exist, it creates memory associated to that index. But if it is an rvalue (like in s2=myclass[s1]; ) and it does not exist, it has to just return null. Memory should not be created (and wasted).
You should not be trying to access an array index that does not exist as an rvalue. You can not return a reference to nothing.
Oct 19 '06 #7
Banfa
9,065 Expert Mod 8TB
Expand|Select|Wrap|Line Numbers
  1. class CharPtr {
  2. public:
  3.     CharPtr& operator = (char* other) {
  4.         if(other== ptr)
  5.             return *this;
  6.         if(ptr)
  7.             delete [] ptr;
  8.         unsigned length = strlen( other);
  9.         ptr = new char[length];
  10.         memcpy(ptr,other,length);
  11.         return *this;
  12.     }
  13. <snipped>
  14. };
  15.  
  16. class T {
  17. private:
  18.     CharPtr a;
  19. public:
  20.     CharPtr& operator[]( const CharPtr& key) {
  21.         return a;
  22.     }
  23. };
  24.  
  25. int main()
  26. {
  27.     T a;
  28.     a["text"] = "putin";
  29.     printf("%s", (char*)a["text"]);
  30. }
  31.  
Although the method is workable as written it will go wrong because in the overload of operator[] you only allocate space for the characters of "putin" you do not allocate space or write a terminating '\0' character so when you cast to (char *) and just use it as a normal C zero terminated string it will go wrong because there is no terminating zero.
Oct 19 '06 #8
dtimes6
73
You should not be trying to access an array index that does not exist as an rvalue. You can not return a reference to nothing.
That is not nothing that is a NULL pointer.
Oct 20 '06 #9
dtimes6
73
Although the method is workable as written it will go wrong because in the overload of operator[] you only allocate space for the characters of "putin" you do not allocate space or write a terminating '\0' character so when you cast to (char *) and just use it as a normal C zero terminated string it will go wrong because there is no terminating zero.
Yes u right. It needs to copy one more char '\0'
Oct 20 '06 #10
Banfa
9,065 Expert Mod 8TB
That is not nothing that is a NULL pointer.
The whole point is it shouldn't be a pointer it should be a reference and you can not return a reference to nothing.
Oct 20 '06 #11
dtimes6
73
The whole point is it shouldn't be a pointer it should be a reference and you can not return a reference to nothing.
But he can return a CharPtr(), that is fine.
Oct 20 '06 #12

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

Similar topics

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...
16
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...
2
by: pmatos | last post by:
Hi all, I'm overloading operator<< for a lot of classes. The question is about style. I define in each class header the prototype of the overloading as a friend. Now, where should I define the...
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...
5
by: Jerry Fleming | last post by:
As I am newbie to C++, I am confused by the overloading issues. Everyone says that the four operators can only be overloaded with class member functions instead of global (friend) functions: (), ,...
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,...
9
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by...
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
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: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
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

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.