C++ Class Design – Vector Classes with Different Element Types

cclass-design

I am trying to design a group of related classes. For example:

  • one table class holds a vector of integer, and has a function returning integers from the vector
  • another table class holds a vector of double, and has a function returning doubles from the vector

Ideally I'd like to have the two classes share the same pointer type, and have the same interface so that they can constructed, and used in a similar way by client. The only difference is that one class is expected to return integer, and the other double.

I have read a few books on design patterns, and I understand the difference between inheritance vs composition. Though I am still a beginner on class design and I suspect I missed something obvious. Below are my questions:

  1. Is it a good practice to have undefined data member or function members? In the sample coding below. The child class will define only part of the data and function member from the base class.
  2. Ideally I would like to have a common interface between the two child classes. however, since function get_value1 from one class returns integer, the other get_value2 from another class returns double, I have to give them a different function name. This is not critical, but can it be avoided?
  3. Should I avoid inheritance and simply create two different classes? especially when the two classes do not share the same user interface?

 

class Base_Table
{
    std::vector<int> vec_int_;
    std::vector<double> vec_dbl_;
    virtual int get_value1(int);
    virtual double get_value2(int i);
};

class Int_Table : public Base_Table
{
    std::vector<int> vec_int_;
    virtual int get_value1(int i) override
    {
        return vect_int_[i];
    }
 };

class Frac_Table : public Base_Table
{
    std::vector<double> vec_dbl_;
    virtual double get_value2(int i) override
    {
        return vect_int_[i];
    }
};

Best Answer

Create a template class. Your use-case is why templates were created. For your example this is quite simple:

template <class T> 
class Table
{
    std::vector<T> vec;
    T get_value(int i) const { 
        return vec[i];
    }
}

But why are you using "get_value" instead of defining operator[] like this:

    T operator[](int i) const {
         return vec[i];
    }
Related Topic