Search code examples
c++classoperator-overloadingsubscriptsubscript-operator

Overloading subscript operator not working as expected


I have a String struct that I overloaded the subscript operator on. But it doesn't seem to work.

//my_string.h

struct String {
    char* Text;
    uint64 Length;

    char& operator[](int32 index); 
}
//my_string.cpp

char& String::operator[](int32 index) {
    ASSERT(index >= 0);
    return Text[index];
}
//main.cpp

String* test = string_create("Hello world");
char c = test[0];

Visual Studio gives me the following error:

no suitable conversion function from "String" to "char" exists


Solution

  • The compiler issued an error because in this statement

    char c = test[0];
    

    the expression test[0] has the type String.

    In this declaration

    String* test = string_create("Hello world");
    

    you declared a pointer instead of an object of the type String.

    If it is not a typo then in this case you have to write

    char c = ( *test )[0];
    

    or

    char c = test->operator []( 0 );
    

    Also it looks strange that the data member Length has the type uint64

    uint64 Length;
    

    while the index used in the operator has the type int32.