Reputation: 441
I have run into a strange problem. When i try to write a function that returns a pointer to a subclass which i swap for a different instance of that subclass i get the "error C2106: '=' : left operand must be l-value" error.
Tthe problems is at the one->getMe() = two;
line :
class subClass{};
class someClass{
public:
subClass * pointer;
someClass(){
pointer = new subClass;
}
subClass * getMe(){
return pointer;
}
};
int main(){
someClass * one = new someClass;
subClass * two = new subClass;
one->getMe() = two;
}
I'm a bit new to c++ so the problem might be horrible simple. Any help is much appreciated.
Upvotes: 0
Views: 784
Reputation: 103733
The pointer that you return from the function is a copy of the pointer in the object. It is a temporary, you cannot assign to it. Even if you could assign to it, it would do no good, because it is no longer connected to the pointer in your object. If you want to be able to assign to the object's pointer after returning it from the function, you want to return the pointer by reference.
subClass *& getMe() {
return pointer;
}
You should also may want to consider adding a const overload in order to work on const objects. It might look like this:
subclass * const & getme() const {
return pointer;
}
Upvotes: 5
Reputation: 1795
The line
one->getMe() = two;
Is trying to assign the pointer at two to one->getMe(). But one->getMe() returns a temporary copy which you cannot assign to. If you want to return the pointer by reference and thus be able to change it then you can use the signature
subClass *& getMe();
as others have suggested.
That being said, you're exposing the inner workings of a class for all and sundry to see and modify, in particular pointers to objects on the heap which may or may not be deallocated correctly which is unwise.
Upvotes: 1