Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to overload [] with two different return types

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading