There are many errors in the code. The main one is that your assignment operator and copy constructor do not completely copy vector pointers to A in general, you are trying to put a B* in the location of the vector. The assignment operator must do this to remove the elements that the vector points to and fill it with deep copies of the elements that the original vector of the object points to after checking for self-determination. Your copy constructor should be filled with deep copies of the elements of the source objects.
Secondly, you must provide a method that adds elements to the vector of your class, and let it set an internal counter variable. The need to coordinate both the vector and the counter from the outside is error prone, and one of the advantages of OOP is to avoid such an error. But even better, remove the counter variable. You do not need it. Then your main will be simplified:
int main() { B Alphabet; for(....) { A* p = new A; //some stuff example p->Member_of_A=3; etc.. Alphabet.appendElement(p); // B takes ownership, no need to delete in main } }
and appendElement may be
class B { public: void appendElement(A* element) { myContainer_.push_back(element); }
You could further improve all of this by storing some sort of separate smart ownership index instead of raw indexes. This would mean that you donβt have to worry about making exceptions yourself. But this is probably beyond the scope of this question.
Now you should avoid pointers. In this case, you do not need to create copy constructors, assignment operators, or destructors. Synthesized compilers will do everything perfectly. Your class B comes down to
class B { public: void appendElement(const A& element) { myContainer_.push_back(element); }
source share