Hope this is not a duplicate. If so, please point me to it in a comment and I'll remove the question again.
I have a data object with data that's only valid in a bundle - i.e. there's no sense in changing the value of one member without invalidating the other members.
This data object describes some image information:
struct ImageInfo
{
ImageInfo(const double &ppix, ...)
: PpiX(ppix),
...
{ }
const double PpiX;
const double PpiY;
const int SizeX;
const int SizeY;
};
In my image object I have a non-const member of type ImageInfo
:
class MyImageObject
{
...
private:
ImageInfo mMyInfo;
}
I want to be able to change mMyInfo
at runtime, but only so that it will take a new ImageInfo(...) instance.
In the MyImageObject::Load()
function, I'd like to read this data from the file info and then create an ImageInfo
instance with the correct set of data:
double ppix = ImageFile.GetPpiX();
...
mMyInfo = ImageInfo(ppix, ...);
But I couldn't manage to write a valid assignment operator (copy constructor is possible of course). My solution left mMyInfo
empty, because I didn't reference this
:
ImageInfo operator=(const ImageInfo &other)
{
// no reference to *this
return ImageInfo(other);
}
Out of curiosity I'd like to know how the assignment operator for such a class would need to look like.
I'm using plain C++.
EDIT
Possible solutions (the goal is to keep the data transportable, but coherent):
Get...()
functions -> simple, but I'd like to avoid the parentheses.ImageInfo *mpMyInfo;
(I'd like to avoid the heap.)I don't think you can have const member variables that aren't static. If you need const variables that change with the instance, you could do something like this:
struct ImageInfo
{
private:
double myPpiX;
double myPpiY;
int mySizeX;
int mySizeY
public:
ImageInfo(const double &ppix, ...)
: myPpiX(ppix),
PpiX(myPpiX),
...
{ }
ImageInfo( const ImageInfo &other)
: myPpiX( other.myPpiX),
PpiX(myPpiX)
...
{ }
const double &PpiX;
const double &PpiY;
const int &SizeX;
const int &SizeY;
// EDIT: explicit assignment operator was missing
ImageInfo& operator=(const ImageInfo &other)
{
myPpiX = other.myPpiX;
myPpiY = other.myPpiX;
mySizeX = other.mySizeX;
mySizeX = other.mySizeX;
return *this;
}
};
The values are stored in the private variables that can be set at construction, and their values accessed by const references. You're also not dependent on the references passed into the constructor living as long as the ImageInfo instance.