Operator Overloading [] & =

Dwibble (10)
I know how to overload operators now, but now I want to know if there's an operator function to combine the [] and = operators to change the value of an encapsulated piece of data, like a node in a queue/stack.

Any suggestions would be great and examples even more welcome.
vlad from moscow (3112)
There are two operators: one is = and other is []. You can combine them in expression to get the needed result.
Last edited on
Dwibble (10)
Could you show me an example? I can't get the implementation right for the life of me.
vlad from moscow (3112)
You wrote in the first post that "I know how to overload operators now". So you should overload two operators: = and [].

SomeClass obj;

obj[0] = SomeValue;
Last edited on
Dwibble (10)
Using this node struct as an example:
1
2
3
4
5
6
struct node
{
    node* next;
    node* prev;
    int data;
};


Would the [] operator return the data, and the = operator is programmed to modify the data in the node?

1
2
3
4
5
6
7
8
9
10
11
// In the main object
int operator[](int index)
{
    return array[index]->data; // Array holding address values of nodes
}

// In the node object
void operator=(int newdata)
{
    data = newdata;
}
vlad from moscow (3112)
I have not understood is it a wrong statement that you know how overload operators? Why are you asking me about this if you know?
Peter87 (3691)
The trick is to let operator[] return a reference
1
2
3
4
int& operator[](int index)
{
	return array[index]->data;
}

No need to overload operator=.
Dwibble (10)
Well, I think I understand it now. Thank you for your time. Sorry if I wasn't clear about some parts.
pogrady (410)
The compiler doesn't resolve everything at the same Time. It does it in steps. In this case it resolves the the [] operator first to returns reference and then assigns the value. Because c++ operates automatically on predefined types, you don't need to overload the = operator. You would though if it returned a user defined type.
Peter87 (3691)
You would only need to do that if the implicitly defined operator= isn't what you want.
Last edited on
Registered users can post here. Sign in or register to post.