Sign in to follow this  
Uphoreum

Return Problem

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this