Jump to content
  • Advertisement
Sign in to follow this  
luasitdown

Is to return a member data good?

This topic is 4651 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

today I suddently sense(I know before) what is wrapper or module. class supply interface to cover/hide many detail or algorithm. if you put data in private and you can only have a way to destroy the idea. that is to return a member data. outside will see the detail of module through intereface. I think it is bad. what do you think about? class A { public: B getB(){return B;} private: B b; } A a; a.getB()->doB_thing. it will exposure B to outside of A.

Share this post


Link to post
Share on other sites
Advertisement
Well, first you are returning a copy of the member data - not the member data itself. You probably want to return by reference - return type B&.

But then outside functions can modify private data - so if you return by const reference "const B&" the outside functions can "inspect" your member data but not change it. Usually that, I would call kosher by object-oriented standards.

Share this post


Link to post
Share on other sites
first of all i think you can make the method a const one so you cant access it... second, you can return a reference, which if im not wrong uses the copy constructure of the class B when you return it and then u use a different copy which is deleted if you dont save it somewhere...

EDIT: haha that wasnt here when i posted... boy im slow :
if i got it ok, then it will expose a copy of B not B itself...

Share this post


Link to post
Share on other sites
References don't use copy constructor, unless you want to get a copy of the object.

For example:


class A
{
B b;

public:
const B& GetB() const {return b;}
};

// used in code
A a;
a.GetB().doB_thing(); // copy constructor of class B is not used

const B& b = a.GetB(); // copy constructor of class B is not used

B otherB = a.GetB(); // copy constructor of class B is used



Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!