0

So here is something I am writing just to get back into code and I can't find the flaw with it.

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;
};

I think I just need a fresh set of eyes to help me out.

4
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by VBNick
0

Your constructor assume an integral type with its initializer

Array(unsigned arraySize):
data(0), size(arraySize)//should be data(). size(arraySize)

Oops, too early. I didn't see that data was a pointer. My bad, please disregard.

This member function, why you returning T()? Shouldn't it be NULL.

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

Edited by gerard4143: n/a

0

So here is something I am writing just to get back into code and I can't find the flaw with it.

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;
};

I think I just need a fresh set of eyes to help me out.

Hi

Your code has no problem, I see none, the only thing that might cause a problem, is where
the getValue method assumes that the template parameter has a default constructor I mean
when use this

return T();

so if T is a type of an object that provides no default constructor , it might cause problem, otherwise your code are OK.

Edited by therockon7throw: n/a

0

compiles fine for me.

edit: if you are using visual studio 2010, there is a bug. If you think your code is wrong because you see red underlines, it's because you haven't included the header with your template in it in any other files yet.

"Error: PCH warning: cannot find suitable header stop location. An intellisense PCH file was not generated"

Edited by VBNick: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.