-
Operator overloading
Code:
class MyClass {
private:
unsigned long len;
unsigned long *data;
public:
// Constructor
// Overloaded Operators
MyClass & operator=(const MyClass &);
MyClass & operator[](unsigned long i);
char * operator[](unsigned long i) const;
bool operator==(const MyClass &other) const;
};
I am trying to implement the [] and == overloading. But am getting seg fault.
char *MyClass:: operator[] (unsigned long i) const
{
return (data[i]);
}
bool MyClass: operator==(const MyClass &other) const
{
for ( i =0; i< len ; i++)
{
if ( this->operator[](i) == other.operator[] (i))
set true;
else
{ set false; break;}
}
return true or false;
}
-
You need to check for going over the array bounds (and, if it happens, what do you want to do about it).
Also, I'm reeeeeeeally hoping that you don't have things like "set true" and "return true or false" in your actual code.
-
Do you return char * for operator[] because you are trying to access the bytes of a long? Currently, the code will treat data like an array of longs, and convert element i of said array to a char pointer.
-
@whiteflags - Yeah, I am trying to return bytes of the 'data' array in the [] overload. How do I do this?
@tabstop: I have actual code to set boolean flags.
-
Since you want to return a bytestring I would do it like so: always access data normally to get the specific long you want. Use bit-wise operators to extract the bits. Those bits you can store in a more convenient object and return that. At the minimum, make an array on the heap of unsigned chars.
-
You haven't shown the constructor for this class. For all we know you might be failing to initialise data or allocating an insufficient amount of memory.
Why is that last function a hybrid between actual code and pseudocode?
If you want a proper diagnosis you have to post the real code.