-1

I have 2 classes for managing 2 queues of different types (something in the form of list<myType1*> and list<myType1*>). To simplify the case, we can use here std::vector<std::string> and std::vector<int> as in the example below:

class StringQueue
{

public:
    StringQueue();
    ~StringQueue();

    int count() const {return m_queue.size();}
    void add(std::string item) {m_queue.push_back(item);}
    void clear() {m_queue.clear();}
    ...etc...

protected:
    std::vector<std::string> m_queue;
};

class IntQueue
{

public:
    IntQueue();
    ~IntQueue();

    int count() const {return m_queue.size();}
    void add(int item) {m_queue.push_back(item);}
    void clear() {m_queue.clear();}
    ...etc...

protected:
    std::vector<int> m_queue;
};

For every Queue class, I have many functions to access the queue (add, clear, count, check, pop one, pop multiple, etc...)

Looking at the code, my question now is: is it possible to use inheritance here? I know I can implement a Queue base class, but only a couple of functions can be derived (count() in the example above) since the m_queue object is different, even if the functions (add, clear, etc...) are the same. Is it possible to have a complete functions inheritance even if the std::vector elements are different?

I'm thinking something like:

class Queue
{

public:
    Queue();
    ~Queue();

    int count() const {return m_queue.size();}
    void add(T item) {m_queue.push_back(item);}
    void clear() {m_queue.clear();}
    ...etc...

protected:
    std::vector<T> m_queue;
};

Is there a way to achieve this?

Max Langhof
  • 23,383
  • 5
  • 39
  • 72
ABCplus
  • 3,981
  • 3
  • 27
  • 43

1 Answers1

2

This is a perfect job for templates:

template<class T>
class MyQueue
{
public:
    MyQueue();
    ~MyQueue();

    int count() const {return m_queue.size();}
    void add(T item) {m_queue.push_back(item);}
    void clear() {m_queue.clear();}
    T popOne()
    {
      T front = m_queue.front();
      m_queue.erase(m_queue.begin());
      return front;
    }
    ...etc...

protected:
    std::vector<T> m_queue;
};

Inheritance is not the right tool for the job, for the reasons you identified yourself.

However:

  1. Why don't you use std::queue and friends, which already do exactly this wrapping?
  2. Why do you want to build a queue based on std::vector - erasing elements from the front involves moving every other element one slot forward. That's about as expensive as it gets...

I recommend you read up more on templates if you want to use them further. While the above code looks nice and easy, writing templated code in C++ has its own set of challenges.

Max Langhof
  • 23,383
  • 5
  • 39
  • 72