Click here to Skip to main content
15,920,633 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a stack and car classes, in the car class I have setters and getters, I want to use them with the push and pop of the stack class, but in the pop function it gives me an error (initial value of reference to non-const must be an lvalue), where k is an object of class car and s is stack object

What I have tried:

this is the pop:
bool pop(T& TopEntry)
	{
		if (isEmpty()) return false;

		TopEntry = items[top];
		top--;
		return true;
	}  // end pop


This is what i'v tried in the main:
while (s.pop(k.GetCarEng()))
	{
		;
Posted
Updated 29-Dec-20 5:34am

You are passing a reference to your function - which means (as the error says) what you pass into the function needs to be something that can be used on the left hand side of an assignment (also known as an lvalue; the bit to the right of the assignment operator is an rvalue):
C++
a = b;
a must be an lvalue: a value that can be changed.
If you wrote this:
C++
666 = b;
You would expect it to fail, because you cannot change teh value of a constant - it is not an lvalue!
Similarly, you can't write this:
C++
foo() = b;
Because you have no idea what foo might return, but it's not going to be anything you can change!
The same requirement is there when you take a reference: because a reference is the object rather than the value of the object changing it can affect the outside world - so you can only ever take a reference of an lvalue for exactly eteh same reasons as above.

Make sense now?
 
Share this answer
 
v2
Comments
CPallini 29-Dec-20 15:37pm    
a == b;
OOOPS!
:-D
OriginalGriff 29-Dec-20 15:40pm    
:O
Fixed.
I think I need new fingers, these ones don't work so well any more when it's cold ...
CPallini 29-Dec-20 15:44pm    
OOOOPS...

#include <iostream>

int g;

int & foo()
{
  return g;
}

int main()
{
  foo() = 42;
  std::cout << g << std::endl;
}
OriginalGriff 29-Dec-20 16:04pm    
Yes, you can return a reference (though please don't, it makes code a PITA to read) - but the OP isn't up to that level yet and I didn't want to confuse him even more.

Let's be honest, neither of us would write the code that way, would me? :laugh:
CPallini 30-Dec-20 1:55am    
"If I could, yes I would
If I could, I would
Let it go"
:-D
BTW have my 5.
You are passing k.GetCarEng() to pop, which is expecting a storage reference that can be updated. If you first assign k.GetCarEng() to a local variable, it should work.

EDIT: What does k.GetCarEng() return? The code is somewhat weird.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900