0

Let's say i have an abstract class thats main purpose is to store a vector of numbers, called NumberVector. Then, I have two classes that inherit NumberVector that are called SortableNumberVector and SearchableNumberVector. Now, I want to make an adapter class that combines these two, and I make a class called SortableSearchableNumberVector, which inherits both of these. I want the final class to call functions from the inherited classes, but still retain data of it's own. Here's how I have laid it out:

class SortableSearchableNumberVector : public SearchableNumberVector, public SortableNumberVector
{
  protected:
       vector<int> numbers;
       int selectedNumber;
  public:
       void selectNumber(int index)
       { SearchableNumberVector::setSelected(index); }

       void sortNumbers()
       { SearchableNumberVector::sort(); }
}

When I run this, the two class variables are unchanged. What is causing this to happen?

w0f
  • 908
  • 9
  • 23
  • 3
    You've ended up with three copies of field `numbers`, and each class' methods work with its own. See "virtual inheritance" and extract `vector numbers` into a common base class. However, it overall looks like a rather bad design. Why don't you use composition instead of inheritance? – yeputons Feb 23 '17 at 01:21
  • This is the way my professor is having me do it. Completely ass-backwards, I totally agree. However, that logic won't get me a passing grade. – w0f Feb 23 '17 at 01:22
  • Then [virtual inheritance](http://stackoverflow.com/a/112474/767632) and common base class `Vector` should do the thing. – yeputons Feb 23 '17 at 01:24
  • Hmm, so I made a base class Vector that holds the data. The two derived classes are `using Vector::numbers;`, but then which of the two classes do I use to use the using keyword for that one? It is required that the final class inherit the searchable and sortable ones and not the base one. – w0f Feb 23 '17 at 01:52

0 Answers0