c++ assignment operator overloading

Hello everyone!

Suppose that I have something like this

A a;
a.mem=new int[100];
A b = a;

where

class A {
public:
 int * mem;
   A() : mem(NULL) { 
   }

  ~A() {
     if (mem!=NULL)
    delete mem;
   }
}

Of course ,because destructor is called two times, I will get a seg fault.
How can i implement an operator overloading function inside class A to allocate memory before copy and avoid seg fault?

I hope you understand my question...

---------- Post updated at 11:37 AM ---------- Previous update was at 11:19 AM ----------

sorry. next time I will use code tags :slight_smile:

Since the class doesn't know how much memory is allocated to mem, you can't. You have to store the size somewhere.

I'd do it like this:

#include <stdio.h>
#include <string.h>

class A {
public:
   int * mem;
   int size;
   A(int isize=0) : mem(NULL), size(0) {
      if(isize > 0)
      {
        mem=new int[isize];
        size=isize;
      }
   }

   A &operator=(const A &o)
   {
      if(size > 0) // Free existing memory
      {
         delete mem;
         size=0;
      }

      if(o.size > 0) // Copy other memory if it exists
      {
         mem = new int[o.size];
         size=o.size;
         memcpy(mem, o.mem, o.size * sizeof(int));
      }

      return(*this);
   }

  ~A() {
     if (mem!=NULL)
     {
       printf("Freeing %p\n", mem);
       delete mem;
     }
   }
};

int main(void)
{
    A a(100), b;

    b=a;
}