1

I have a classA which has a vector< classB* > vObject.

class ClassA{
public:
     ClassB** operator [] (int index);
private:
     vector<ClassB*> vObject
};

Let's Assume that vObject is filled with some classB* objects. What I want to do is to be able to replace classB* elements of vector like that:

classA_obj[3] = classA_obj[5];
classA_obj[1] = classB_obj;

I tried to return a pointer of ClassB Element. Here is my current operator implementation:

ClassB** ClassA::operator [](int index){
    return &vObject[index]; }

After that i tried the following:

*classA_obj[3] = *classA_obj[5]

The code of doing all the work with just a vector would be:

vector<ClassB*> vObject;
vObject.push_back(new ClassB(ARG1,ARG2));
vObject.push_back(new ClassB(ARG1,ARG2));
vObject[0] = vObject[1];

I'm really confused about this, I thought my code was right but it actually doesn't work. I would love if someone could tell me what I'm doing wrong.

The above code is just a sample of my actual code.

George Sofianos
  • 1,141
  • 1
  • 13
  • 26

3 Answers3

2

If you return a reference, you will be able to do the replacement you requested.

class ClassA{
public:
     ClassB*& operator [] (int index) { return vObject[index]; }
private:
     std::vector<ClassB*> vObject
};

However, the way you have described your usage seems to indicate you can easily change your vector to hold ClassB objects instead of pointers.

class ClassA{
public:
     ClassB& operator [] (int index) { return vObject[index]; }
private:
     std::vector<ClassB> vObject
};

Then instead of pushing new ClassB into the vector, you just push ClassB:

vObject.push_back(ClassB(ARG1,ARG2));
vObject.push_back(ClassB(ARG1,ARG2));

This has the advantage you not needing to explicitly visit your container to delete the pointers. Otherwise, you will need to update ClassA to obey the rule of three.

Community
  • 1
  • 1
jxh
  • 69,070
  • 8
  • 110
  • 193
  • Thanks, changing ClassB** to ClassB*& worked. My whole application depends on ClassB with pointer and I made some code to delete the pointers in the vector, so I will stick with that but thanks for the info. – George Sofianos Aug 09 '12 at 14:22
0

The ordinary std::vector returns a reference, so you should probably try that:

ClassB*& ClassA::operator [](int index)
{
     return vObject[index]; 
} 
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
0
In the definition:
class A {
  public:
          ClassB*& operator [] (int index) { return vObject.at(index); };
  private:
          vector<ClassB*> vObject;
}

It's a inline function, nothing else to be done. However, I would check index just for sanity.

cybertextron
  • 10,547
  • 28
  • 104
  • 208