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.
If you return a reference, you will be able to do the replacement you requested.
However, the way you have described your usage seems to indicate you can easily change your vector to hold
ClassBobjects instead of pointers.Then instead of pushing
new ClassBinto the vector, you just pushClassB:This has the advantage you not needing to explicitly visit your container to delete the pointers. Otherwise, you will need to update
ClassAto obey the rule of three.