Jump to content

  • Log In with Google      Sign In   
  • Create Account

Class within a Class


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 PragmaOnce   Members   -  Reputation: 744

Like
0Likes
Like

Posted 02 April 2013 - 05:27 PM

Hey guys.
 
As far as I understand when working with classes, members should always be kept private and then you should have functions in the public section that manipulates this data. But what if you have a class within a class, for example:

 

class Player
{
  public:
  Inventory backpack;
}

--------------------------
Somewhere in the game
---------------------------
{
  player.inventory.addItem(apple);
}

 

 

Would it still be considered bad practice if the class that is contained within still has it's members encapsulated?



Sponsor:

#2 JTippetts   Moderators   -  Reputation: 8491

Like
12Likes
Like

Posted 02 April 2013 - 06:10 PM

Would it still be considered bad practice if the class that is contained within still has it's members encapsulated?

Typically, you don't "hide" the members of the class behind the facade of private just to be a bully. You do it to preserve invariants.

Say you have a class Foo with a member bar_. bar_ has to be in the range of 14 and 76. The invariant here, then, is that 14>=bar_>=76. In order to preserve that invariant, you need to strictly control access to bar_. Setting it public, and allowing outside code to modify bar_ willy-nilly, can possibly lead to the invariant being violated, and the behavior of Foo being adversely affected as a result. So you specify that bar_ can only be accessed through methods designed to preserve the invariant (in this case, bounds checking the input and either correcting/clamping to range, or throwing an exception).

If allowing backpack to be exposed to the general public can't possibly violate any invariants of Player, then there is no harm in having it be public, and in fact setting it behind trivial accessor functions out of some misguided need to make all members private is making unnecessary work for yourself. But if the proper operation of Player relies upon strictly controlling access to backpack, then it should be walled away and protected behind a proper access interface so that the outside world doesn't meddle with things they don't understand.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS