DFlorin
DFlorin

Reputation: 1

Explicit invocation of ctor for allocation of memory

Consider the following class:

class Vector{
    int dim; //dimension of array v
    Complex* v; //Complex is another class
 public:
    Vector(int dim = 0):dim(dim){(dim)?(v=new Complex[dim]):(v=nullptr);}
    Vector(int dim, const Complex* c):dim(dim),v(new Complex[dim]){
        for(int i=0;i<dim;i++) v[i]=c[i];}
    Vector(const Vector& a):dim(a.dim),v(new Complex[a.dim]){
        for(int i=0;i<dim;i++) v[i]=a.v[i];}
    ~Vector(){if(dim)delete [] v,v=nullptr;}
    friend Vector& operator >> (Vector& is,Complex& z){
        Vector copie(is);
        is.~Vector();
        is.Vector::Vector(is.dim+1);}
};

I try to overload the >> operator in order to add elements to v. My idea was to create a copy, then call dctor and the ctor for the object to be modified via >> operator. I'm stuck after getting this error:

In function ‘Vector& operator>>(Vector&, Complex&)’:
main.cc:56:20: error: cannot call constructor ‘Vector::Vector’ directly
         is.Vector::Vector(is.dim+1);

I'm not allowed to use containers!! Please help me!

Upvotes: 0

Views: 47

Answers (2)

R Sahu
R Sahu

Reputation: 206707

There is no need for calling the destructor and calling the constructor. Steps you can take to make your function work:

  1. Allocate memory to hold the current objects plus the additional object.
  2. Copy the objects from the old memory location to the new memory location.
  3. Delete the old memory.
  4. Associate the newly allocated memory with the input object.

friend Vector& operator>>(Vector& is, Complex& z){

   // Allocate memory 
   Complex* vnew = new Complex[dim+1];

   // Copy objects to new memory.
   std::copy(is.v, is.v + is.dim, vnew);
   vnew[is.dim] = z;

   // Delete the old memory.
   delete [] is.v;

   // Use the new memory
   is.v = vnew;

   // Increment dim.
   is.dim++;

   return is;
}

Having said that, I think you are using the wrong function to insert an element to Vector. operator>> is for extracting data from. operator<< is for inserting data to. You should use operator<< to insert an element to a Vector.

friend Vector& operator<<(Vector& is, Complex const& z){
  ...
}

Upvotes: 0

alfC
alfC

Reputation: 16270

That's right, you can't call the constructor directly. Probably you want to use placement new.

friend Vector& operator >> (Vector& is,Complex& z){
    Vector copie(is);
    is.~Vector();
//    is.Vector::Vector(is.dim+1);
    new(&is) Vector(is.dim + 1);
    return is;
}

Even then the code may not be semantically correct.

Having said that, this is not the recommended way to do it for the last 20 years. Watch this Jon Kalb "Exception-Safe Code, Part I" for an explanation (the example is almost the same). The recommended way is to implement this in terms of other operations like copy or swap.

Minor syntactic detail, operator>> is confusing, use operator<< at worst.

Upvotes: 1

Related Questions