Search code examples
c++vectoroperator-overloadingcopy-constructordelete-operator

Assignment operator and Copy Constructor


I had recently asked a question somewhat related to this one, but it was horridly worded and I had no clue what I was doing. I got some time to play around with code and hope this question makes more sense. Nevertheless something is still going on wrong. I have a class B. A pointer (*p) to that class. I just want to make a copy of this pointer ( say called q). Delete p but still have q a valid pointer pointer to that same information that p was pointings too. Then delete q. When I try to set them equal to each other I get issues

class B
{
    public:
    B(); ~B();
    B(const B &Overloading);
    B& B::operator=(const B &Overloading);
    vector<*A> stores_a; //class A contains ints, doubles etc. I filled this with
    //pointers to class A
    void Mr_Clean();
};

B::B() {}
~B::B()
 {
    Mr_Clean();
 }
 B::B(const B &Overloading)
 {
     for(size_t i=0; i<stores_a.size(); i++)
     {
         stores_A[i]=new A(*Overloading.stores_a[i]);
     }
  }
B::B& B::operator=(const B &Overloading)
  {
      if(this!=&Overloading)
      {   Mr_Clean(); 
          for(size_t i=0; i<stores_a.size(); i++)
          {
              stores_A[i]=new A(*Overloading.stores_a[i]);
           }
      }
      return *this 
 }
 void B::Mr_Clean()
 {
    for(size_t i=0; i<stores_A.size(); i++)
    {
        delete stores_A[i];
    }
 }
 int main()
 {
       B *p=new B;
       B *q=new B;
       // fill some stuff. this is just random stuff I am making up
       *q=*p; //compiles then Kaboom at this line
        delete p;
        delete q;
      return 0;
  }

I guess I have some conceptual gap still on the assignment operator. I have read many tutorials and I feel like I am doing what they say...

Also another question, say in this example I also had a member int x in B. Since I called the copy constructor and overloaded the assignment operator do I have to explicitly call x=Overloading.x? I mean technically I am overriding the default copy constructor no? However x is just a regular plain old int.


Solution

  • I see two issues here:

    1. You don't resize destination vector. But this doesn't cause any errors at the moment because
    2. You use size of destination vector to loop through items of source vector. And this can cause runtime error.

    You could try using this code to copy vectors:

    stores_a.resize(Overloading.stores_a.size());
    for(size_t i=0; i<Overloading.stores_a.size(); ++i)
    {
        stores_a[i]=new A(*Overloading.stores_a[i]);
    }
    

    or this one (though the one above should be faster for general case):

    stores_a.clear();
    for(size_t i=0; i<Overloading.stores_a.size(); ++i)
    {
        stores_a.push_back(new A(*Overloading.stores_a[i]));
    }