0

I can not write copy constructor. How to fix the error?

Tried to fix it like that:

template<typename T, typename A>
vector<T, A>::vector(const vector<T, A> &other)
{
    this->allocator_ = other.allocator_;
    this->size_ = other.size_;
    this->space_ = other.space_;
    this->data_ = other.allocator_.allocate(other.space_);

  std::copy(other.data_, other.data_ + other.size_, this->data_);
}
template <typename T, typename A = std::allocator<T>>
struct vector_base
{
  A    allocator_;
  int  size_;
  int  space_;
  T*   data_;

  vector_base(A const& alloc, int n)
      :allocator_(alloc)
  {
    if (n > 1)
    {
      data_ = allocator_.allocate(n); size_ = 0, space_ = n;
    }
    else
    {
      data_ = allocator_.allocate(8); size_ = 0, space_ = 8;
    }
  }

  ~vector_base() {allocator_.deallocate(data_, space_);}
};
class vector : protected vector_base<T, A> 
{
  vector(vector<T, A> const &v);
  vector<T, A>& operator=(vector<T, A> const &v);
};

template<typename T, typename A>
vector<T, A>::vector(const vector<T, A> &other)
  : allocator_(other.allocator_), size_(other.size_), space_(other.space_), data_(other.allocator_.allocate(other.space_))
{

  std::copy(other.data_, other.data_ + other.size_, this->data_);
}

template<typename T, typename A>
vector<T, A> &vector<T, A>::operator=(vector<T, A> const &v)
{
  if (this != &v)
  {
    vector<T, A> copy_vector(v);
    copy_vector.swap(*this);
  }
  return *this;
}

error: class ‘vector’ does not have any field named ‘allocator_’ : allocator_(other.allocator_), size_(other.size_), space_(other.space_), data_(other.allocator_.allocate(other.space_))

JDbP
  • 53
  • 4
  • `allocator_`, `size_`, `space_`, `data_` are members of `vector_base` but you try to initialize them in constructor of derived `vector`. That's not allowed. You had to put them into copy constructor of `vector_base` or change them into a plain assignment if you want to have them in `vector::vector()`. – Scheff's Cat Jun 15 '19 at 07:54
  • You can't write any constructor in this way. – L. F. Jun 15 '19 at 08:59

0 Answers0