user667143
user667143

Reputation:

OOP design - inheriting from container with generic type

I have two classes, say CollectionA and CollectionB, both inheriting from a Collection. Collection has an std::array<GenericType> attribute. I want to use CollectionA as a Collection whose inherited std::array contains elements of type ClassA (std::array<ClassA>) and CollectionB as containing an std::array<ClassB>. Is this possible, and if so how can I implement this design?

Note: I am not familiar with templates, if they are required for this problem.

EDIT: Collection is user-defined, so I'm not directly inheriting from std::array

Upvotes: 0

Views: 77

Answers (3)

Daniel Frey
Daniel Frey

Reputation: 56883

A template would be the obvious solution, start with

template<typename Element>
class Collection
{
protected:
    std::array<Element> arrr_;
};

class CollectionA : public Collection<ClassA>
{
};

class CollectionB : public Collection<ClassB>
{
};

Hope it helps...

Upvotes: 2

user258808
user258808

Reputation: 734

  template <class T>
  class Collection {
    protected:
      std::array<T> data_;
  };

  class CollectionA : public Collection<A> {
   /*
    you can use data_ in this class. 
    data_ will be of type std::array<T>;
   */
  };

Upvotes: 0

Alex Chamberlain
Alex Chamberlain

Reputation: 4207

Define them as so

class ContainerA : public Container<ClassA> {...};
class ContainerB : public Container<ClassB> {...};

Upvotes: 1

Related Questions