ml4irs
ml4irs

Reputation: 21

Overloading a member function to receive an assigned value?

I want to create two methods of a class that access and modify some data in that instance.

For example:

int val = image.at(row, col);
image.at(row, col) = 255;

Is there a way to overload the function so it allows assignment when calling image.at(row,col)?

Upvotes: 1

Views: 70

Answers (1)

cigien
cigien

Reputation: 60460

You don't necessarily need to write 2 methods for this. So long as at returns a value that can be assigned to (i.e. an l-value), the same function will work to both access and modify the data:

struct Image 
{
   int& at(int, int);
// ^^^^ 
};

However, you should provide an overload for the case when the object whose data you want to access is a const object:

struct Image 
{
   int& at(int, int);
   int const& at(int, int) const;  // for const objects
};

Upvotes: 3

Related Questions