Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error C2100 - Illegal Indirection

I have a very simple program written to define a * operator in an array template class. When I try to compile it gives me an error "illegal indirection". Any help on the matter would be greatly appreciated!

This is the operator definition:

template <typename T>                                                                   
NumericArray<T> NumericArray<T>::operator * (const int factor) const
{
NumericArray<T>* TempArray2 = new NumericArray<T>(Size());
for (int i=0; i<Size(); i++)
{
    *TempArray2[i] = ((GetElement(i))*(factor));
}
return *TempArray2;
}

And this is the implementation in the test main function:

cout<<((*intArray1)*5).GetElement(0);                                   
cout<<((*intArray1)*5).GetElement(1);
cout<<((*intArray1)*5).GetElement(2);

Any ideas?

like image 746
Byron Avatar asked Apr 22 '13 12:04

Byron


2 Answers

Don't forget your operator precedence rules. It seems that you want:

(*TempArray2)[i]

Otherwise your expression *TempArray2[i] is considered as *(TempArray2[i]) and I suppose your NumericArray<T> type doesn't have the unary * operator overloaded.

like image 144
Joseph Mansfield Avatar answered Nov 07 '22 15:11

Joseph Mansfield


In *TempArray2[i], the * is applied to TempArray[2] because of the precedence rules, and there's a fair chance that the array elements don't have a unary * operator.

But your use of dynamic allocation and then dereferencing to return by value means that you have a memory leak.
(You don't need new to create objects in C++ - you probably don't need to use it in main either.)

This would be better (and avoids the whole indirection issue):

template <typename T>                                                                   
NumericArray<T> NumericArray<T>::operator * (int factor) const
{
    NumericArray<T> TempArray(Size());
    for (int i = 0; i < Size(); i++)
    {
        TempArray[i] = GetElement(i) * factor;
    }
    return TempArray;
}
like image 2
molbdnilo Avatar answered Nov 07 '22 15:11

molbdnilo