class template operator confusion

Joined
Jan 27, 2011
Messages
2
Reaction score
0
Hi

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;
however, I have a class trying to use one of these myArrays, but I want to declare it as follows:
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:
Joined
Jan 27, 2011
Messages
2
Reaction score
0
I seem to have a bit more luck if I use
Code:
 (*xvals)[i]=x;
is this the way to go, or am I over complicating things?

btw I create xvals like so

Code:
xvals=new myArray<double>(512);
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top