'=' left operand must be a lvalue

Hi guys.

I'm trying to make my own String class.
The thing I can't understand is why when I write

1
2
GString my("sprint");
my[5] = 'g';


The compiler says '=' left operand must be a lvalue

These are the Constructor and the operator overloading of the GString Class:

1
2
char* mainString;
int size;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* CONSTRUCTOR */
GString(const char* CstyleString)
{
	// +1 for the NULL character at the end (/0)
	size = strlen(CstyleString) + 1;
	mainString = new char[size];

	int i = 0;
	// -1 because we want to set the NULL character AFTER the copy of the character from one vector to another
	for (i = 0; i < size - 1; i++)
		mainString[i] = CstyleString[i];

	mainString[i] = '\0';
}

/* OPERATOR OVERLOADING */
char operator[](int Index)
{
     if (Index >= 0 && Index < size)
	return mainString[Index];
}

const char operator[](int Index) const
{
	if (Index >= 0 && Index < size)
	    return mainString[Index];
}

GString& operator=(const GString& other)
{
	size = other.size;

	delete[] mainString;
	mainString = new char[size];

	for (int i = 0; i < size; i++)
	{
	    mainString[i] = other.mainString[i];
	}

	return *this;
}


Any tip?

P.S: I KNOW what is a lvalue and a rvalue, but I think there's a bug in the operator overloading...




Last edited on
char& operator[](int Index)
Whut!? That was the problem!

But why does it work if it returns a reference?
Because you were returning a r-value when a l-value was needed.

By the way, you have undefined behaviour if `Index' is outside the [0; size) range

By the way, you have undefined behaviour if `Index' is outside the [0; size) range


That was just a precaution. I'm gonna remove that then...

Thanks =)
Topic archived. No new replies allowed.