Pergunta

I have an abstract class list:

template <class V>
class List {
public:
  void toArray(void*) const = 0;
// other methods
};

And I have an inherited class arraylist:

template <class V>
class ArrayList:
  public List<V>
{
public:
  ArrayList(const List<V>&);
  void toArray(void*) const;
private:
  ArrayList(const ArrayList&); //Remove default copy ctor
// other methods and functions
};

When calling ArrayList(const ArrayList&) I would like to use the constructor for ArrayList(const List&).

LinkedList<int> link; // also inherited from list
// populate list
ArrayList<int> lst = link; // works fine
ArrayList<int> newList = lst; // error ctor is private

I would not like to rewrite the code in ArrayList(const List&) for ArrayList(const ArrayList&) because they both use the same toArray(void*) method declared in List. How do I do this? I would also like to avoid calling the default ctor of ArrayList because it allocates a minimum sized array of 8 values.

Foi útil?

Solução

template <class V>
class ArrayList: public List<V>
{
public:
  ArrayList(const List<V>&);

  // use delegating constructor (C++11 feature)
  ArrayList(const ArrayList& val) : ArrayList( static_cast<const List<V>&>(val) ) {}

  void toArray(void*) const;
private:
};

If your compiler does not support C++11:

template <class V>
class ArrayList: public List<V>
{
public:
  ArrayList(const List<V>& val) { construct(val;) }
  ArrayList(const ArrayList& val) { construct(val;) }
  void toArray(void*) const;
private:
  void construct(const List<V>&);
};
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top