Hi
C programmer here, new to c++ so go a bit easy please.
I am playing around with an array template, for example:
I have overloaded the subscript operator as below:
All is good if I use the template like:
however, I have a class trying to use one of these myArrays, but I want to declare it as follows:
In this case I create xvals in the Someclass constructor using new.
However when I call foo, the subscript operator [] for myArray is never reached, and instead the destructor is called..wtf?
I presume this is because I've used
I did this so in the constructor I can use new with a size. C instinct tells me not to put the entire myArray object inside the Someclass - is this wrong? plenty of examples seem to use pointers to classes in this way. it's also a way to leave creating the class until I know how big I want the data to be. Do I need to overload the [] operator in a different way?
Many thanks for your kind and not at all judemental help..
C programmer here, new to c++ so go a bit easy please.
I am playing around with an array template, for example:
Code:
template <typename T>
class myArray
{
public:
myArray(void);
myArray(unsigned size);
/* copy constructor */
myArray(const myArray<T> &orig);
~myArray(void);
int size(){return used;}
T *raw(){return data;}
void clear();
T &operator[](unsigned index);
private:
unsigned used;
unsigned allocd;
unsigned realloc_amount;
T* data;
};
I have overloaded the subscript operator as below:
Code:
template <typename T>
inline T& myArray<T>::operator[](unsigned index)
{
printf("in array operator[%d]\n", index);
if(index >= allocd)
{
int newsize=index+realloc_amount;
if(!allocd)
data=new T[newsize];
else
{
T* new_data=new T[newsize];
for(int i=0; i < used; i++)
new_data[i] = data[i];
delete[]data;
data=new_data;
}
allocd=newsize;
}
used=std::max<unsigned>(used, index+1);
return data[index];
}
All is good if I use the template like:
Code:
myArray <int> test(26);
test2[4]=5;
Code:
class Someclass
{
public:
..snip..constructor etc..
void foo(unsigned bar, double val) { xvals[bar]=val; }
private:
myArray <double> *xvals;
};
In this case I create xvals in the Someclass constructor using new.
However when I call foo, the subscript operator [] for myArray is never reached, and instead the destructor is called..wtf?
I presume this is because I've used
Code:
MyArray <double> *xvals;
I did this so in the constructor I can use new with a size. C instinct tells me not to put the entire myArray object inside the Someclass - is this wrong? plenty of examples seem to use pointers to classes in this way. it's also a way to leave creating the class until I know how big I want the data to be. Do I need to overload the [] operator in a different way?
Many thanks for your kind and not at all judemental help..
Last edited: