0

It's my first time using templates and for some reason my program stops running, with a message that says "a problem caused the program to sop working correctly". I don't really know what's causing it.

Here's the main:

class point
{
    int x;
    int y;
public:
    point(int abs=0,int ord=0)
    {
        x=abs;
        y=ord;
    }
    ~point(){}
};

the template:

template <class T>
class tablo
{
    T *adr;
    int nelem;
public:
    tablo();
    ~tablo();
    T nouvo(T);
    T & operator [](T);
};

template <class T>
tablo<T>::tablo()
{
    nelem=0;
    adr=new T[nelem];
}

template <class T>
tablo<T>::~tablo()
{
    delete[] adr;
}

template <class T>
T tablo<T>::nouvo(T var)
{
    return adr[nelem++]=var;
}

template <class T>
T & tablo<T>::operator[](T var)
{
    return[T]
}

and the main:

#include <iostream>
#include "point.h"

void main()
{
    tablo<point> tab;

    point a(1,2);
    point b(3,4);

    tab.nouvo(a);
    tab.nouvo(b);
}
  • 1
    It's not causing this particular problem, but you need to either learn the [Rule of Three](http://stackoverflow.com/questions/4172722), or use `std::vector` and save yourself a world of pain. – Mike Seymour Oct 10 '13 at 15:28

2 Answers2

8

You are creating a size zero (!) array here:

template <class T>
tablo<T>::tablo()
{
    nelem=0;
    adr=new T[nelem];
}

and you access it and write beyond its bounds here:

template <class T>
T tablo<T>::nouvo(T var)
{
    return adr[nelem++]=var;
}

Any attempt access to a dynamically allocated zero size array is undefined behaviour, meaning pretty much all you can safely do is call delete on it and take its address. See when is a zero length array OK?

Plain arrays do not magically grow in size. You could simplify everything by using std::vector<point> instead of, or as a part of, tablo.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2
nelem = 0;
adr = new T[nelem];

Here you're allocating a zero-sized array and later on in your program you try to access values that are beyond that size.

The default-constructor should set the array to nullptr and you should have another constructor that takes the specified size:

template <class T>
tablo<T>::tablo()
    : nelem(0), adr(nullptr)
{ }

template <class T>
tablo<T>::tablo(int size)
    : nelem(size), adr(new T[size])
{ }
David G
  • 94,763
  • 41
  • 167
  • 253