Click to See Complete Forum and Search --> : Problem with overloaded operators, templates and inheritance


bleakcabal
03-19-2004, 12:38 AM
Hi !

I have a base class and a derived class ( which inherits the base class ).

I want to derived class to overload the [] operator, so that it can perform certain operations and also call the [] operator of the base class. I have used to BaseClass before and I know it isn't the source of the problem. I have abreviated some code with ( ... ) when I felt it was not necessary to put said code.

Here is what I have done so far :

Code :
DerivedClass.h

template <typename T>
DerivedClass : public BaseClass<T>
{
public :
...
...
...
T &operator[] (int param);
};


DerivedClass.cpp
...
...
...

template <typename T>
T &DerivedClass<T>::operator[] (int param)
{
...
...
...
}


Main.cpp
...
DerivedClass test();
...
test[i] = 12;
...


But I get a Segmentation Fault everytime I run the program.
I have removed all code in the overloaded operator [] in the derived class so I know this is not the problem.
If I call test[i] = 12 I get a segfault even if [] does not have any code in it's implementation.
If I don't call [] I don't have any problems.
I have tried different values, etc. but after some extensive testing I can see the problem is not there.

I have no idea what I could be doing wrong... but I really have close to no experience overloading operators and working with templates so I'm no surprised it's not working.

I would appreciate any help you could give me, thank you in advance !

bwkaz
03-19-2004, 08:11 PM
Compile your program with the extra -g switch, and run gdb /path/to/resulting/executable. Then run to start it up, and gdb will get control back when the segfault occurs. Do a bt to see a stack backtrace (the list of functions that have called each other, up to the one that's currently executing), and do a list if the current function (the one at the top) is one that you wrote. If not, then do an up until the current function is actually one you wrote, and then do a list to see some context.

If the segfault is in free(), then you're likely freeing the same memory twice.

If the backtrace is extremely long (as in many thousands of function calls), then the segfault might be due to a stack overflow -- try to reduce the recursion level or reduce the number of local variables required by the functions involved.