Override [] operator for a class

Hi, I have a Basket class, containing Apple objects, stored in an Basket.
A Apple object is described by coordinates x, y.
I'm trying to override the [] operator, but it's not working:
Basket2[0] = Apple1; // Not working: no operator "=" matches this operand, operand types are Basket = Apple

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Basket
    {
    private:
    	Apple* m_data;
    	int m_size;
    
    public: 
    	Basket(); //default Constructor
    	Basket(int size); //argument constructor 
    	Basket(const Basket &Basket); //copy constructor
    	~Basket(); //destructor
    
    	Basket& operator = (const Basket& source); // Assignment operator
    	Apple& operator[](int index); //class indexer for writing
    	const Apple& operator[] (int index) const; //class indexer for reading
    
    	//Getter function
    	int Size() const; //returns size 
    
    	//Get element by index
    	Apple& GetElement(int i);
    
    	void SetElement(const int index, const Apple& element); //set element of Basket to a new Apple
    
    	void Print(string msg);
    };
    
    //class indexer
    Apple& Basket::operator [] (int index)
    {
    	return (index > m_size - 1) ? m_data[0] : m_data[index];
    }
    
    
    const Apple& Basket::operator [] (int index) const
    {
    	return (index > m_size - 1) ? m_data[0] : m_data[index];
    }
    
    int main()
    {
      //instantiate a Basket of two elements size
    	Basket* Basket1 = new Basket(2);
    	Apple Apple0(0, 0); //instantiate a Apple with coordinates x, y
    	Apple Apple1(1, 1);	
    	Basket1->SetElement(0, Apple0); //set the first element of Basket1 to Apple0
    	Basket1->SetElement(1, Apple1);
    	Basket* Basket2 = new Basket(2);
    	Apple Apple2(2, 2); //instantiate a Apple with coordinates x, y
    	Apple Apple3(3, 3);
    	Basket2->SetElement(0, Apple2); //set the first element of Basket1 to Apple2
    	Basket2->SetElement(1, Apple3);
    	Basket2[0] = Apple1;  // Not working: no operator "=" matches this operand, operand types are Basket = Apple
      return 0;
    }
Last edited on
The problem is that array1 and array2 are pointers, not Array objects.
You don't need to create your Array object itself with new, that's the beauty of RAII.

Just do:
1
2
3
4
5
6
Array array2(2);
// ...
array2.SetElement(0, point2);
array2.SetElement(1, point3);

array2[0] = point1;

Yes, but if I want to use objects on the heap ?
Yes, but if I want to use objects on the heap?

Dereference your Array* to obtain an Array.
(*array2)[0] = point1;
Topic archived. No new replies allowed.