Assume a bytes buffer on the heap:
BYTE *Buffer = new BYTE[128] ;
Sometimes I need a BYTE:
BYTE x = Buffer[5] ;
Sometimes I need a pointer to part of the buffer, e.g. to map a structure against:
MyStruct *Str = (MyStruct*)&Buffer[5] ;
If I want to mimic this in a class:
class MyBuffer
{
public:
MyBuffer() { Buffer = new BYTE[128] ; }
~MyBuffer() { delete[] Buffer ; }
BYTE operator[](int Index) const { return Buffer[Index] ; }
// BYTE *operator[](int Index) const { return &Buffer[Index] ; }
BYTE *Buffer ;
};
Situation 1. would work, but not 2.
MyBuffer Buffer ;
BYTE x = Buffer[5] ; // Works
MyStruct *Str = (MyStruct*)&Buffer[5] ; // Won't work
I can’t implement two variants of the same operator that only differ in return type.
So I wonder, is what I ask possible ?
>Solution :
You can just change the return type to be a reference type(lvalue ref to be particular) as shown below. This works because a function call like f() where f returns by lvalue-reference is an lvalue and we can apply operator& to an lvlue.
class MyBuffer
{
//--v------------------------->return by reference
BYTE& operator[](int Index) const
{
return Buffer[Index] ;
}
//other code as before
};
MyStruct *Str = (MyStruct*)&Buffer[5] ; // compiles now