Search code examples
c++arraysclasstemplatesdefinition

What should be the answer of this question?


Note: I got this question from a friend of mine. It was given to him in an interview exam. I'd done programming in C++ in my early days of university. Even though the question looked easy on the first glance, I couldn't find a good answer to it. That's why I'm asking here.

Given this C++ code below, please answer to the following 3 questions:

  • What is the class supposed to do?
  • There’s a major problem in the implementation of the class. Can you name it?
  • Can you give 3 different ways of fixing this problem (Depending on the requirement specifications of that class)?
    template<typename T>
    class Array
    {
     public:
        Array(unsigned arraySize):
            data(0), size(arraySize)
        {
            if(size > 0)
                data = new T[size];
        }
        ~Array()
        {
            if(data) delete[] data;
        }

        void setValue(unsigned index, const T& value)
        {
            if(index < size)
                data[index] = value;
        }

        T getValue(unsigned index) const
        {
            if(index < size)
                return data[index];
            else
                return T();
        }

     private:
        T* data;
        unsigned size;
    };

Solution

    1. This class encapsulates an array of any kind of values. Similar to RAII [See Here}
    2. There is no copy semantics.
    3. Ways to fix this problem

      • Use std::vector
      • Implement "The rule of three"/"The rule of five"/"The rule of zero" [See Here]
      • Enable changing the size of the array after constructing it.
      • Initialize with nullptr
      • Instead of integer, use std::size or size_t
      • Change the name of the variable size which might conflict with std::size when using namespace std is used.
      • Replace if(data) delete[] data; with delete[] data; when nullptr is used to initialized the values.
      • Implement throwing of std::out_of_range in getValue and setValue

    Answered by: Bethsheba, Slava, Jesper Juhl, Vlad from Moscow , eerorika