Return Problem

Started by
4 comments, last by Zahlman 17 years, 9 months ago
I'm confused. So, I have a class that has an image as one of it's variables, and I have a function that returns it. But, I need to be able to modify it, so I don't just want it to return a copy of that image, I want it to return the image itself so that when I modify it, it will modify the image, not just a copy. I suppose I could just return it, modify it, and send it back, but I think theres a way to send the actual variable instead of just a copy right? While we're on the subject, everyone seems to say that you should make your classe's variables private, then make functions to return them. Why is that? Or is that not true?
Advertisement
The reason that you should make the data private is that using the member functions provides an easier interface. It also provides a way for you to make sure that the data are not changed in a way that they should not be.

That said, if you always want to be able to modify the image, and it won't compromise your design, just make it public.
That's kinda what I thought the reason was. Thanks!
Im not sure what your "Image" variable is without code, but if you allocated it in the constructor

protected:
Image* mpImg;

In ctor "mpImg = new Image(width, height);" something like this. Create an access function that just returns the pointer "return mpImg;" change it through the return pointer.

Image* GetImage() { return mpImg; }

If your class just contains the variable

protected:
Image mImg;

you can return a reference to the image and change it through the reference

Image& GetImage() { return mImg; }

not sure if this is exactly what you were asking or not. Accessor functions are used to separate the objects "guts" from how they are used. Say somewhere down the road your "Image" is moved into another object within another variable

protected:
Model mModel; // model contains image

the underlying code of "Image* GetImage();" could easily be changed to something like "Image* GetImage() { return mModel.GetImage(); }" without requiring you to change any of the code outside. Hope thats clear.
Yep, I got it working. Thanks!
Why is the outside code modifying the image? Why can't the object modify its own image instead?

This topic is closed to new replies.

Advertisement