I’m working on an small C++ example, to learn C++. Somebody wrote the main function already which looks like this:
int main()
{
map2d p1(1.,3.);
const map2d p2(0.,0.);
p1.x(); // testing the access to member variable
p2.x(); // testing the access to member variable
p1.x() = 3.; // changing the member variable
return 0;
}
Okay. I created a class with the name map2d. Which works so far up to the point where the member variable has to be changed p1.x() = 3.;. My question is, how to do it? My class looks like this this:
class map2d
{
private:
double xp, yp;
public:
map2d (double xnew, double ynew): xp(xnew), yp(ynew) {}
double x() const { return xp; } // here is my problem
};
I was thinking to return a reference with &, but this didn’t worked out. I used something something like:
double& x() const { return xp; }
Did I make something wrong? Do you have any idea how to do it?
You can’t return a modifiable l-value reference to a non-mutable class member variable from a method that is labeled as being
const. By labeling a method asconst, you are telling the compiler that it doesn’t change any data members that aren’t labeled asmutable, nor does it call any class methods that can change the state of non-mutable class members.You basically need two overloaded versions of your accessor function:
Which version of the overloaded function will be chosen depends on the context of the call to the class method. This is based on whether the class instance for which the method is being called from is a constant or mutable class reference. For instance: