Thread: Protected / Private Variables accessable.

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    69

    Protected / Private Variables accessable.

    Yop guys,

    I have this bizzare (to me) question. I have a simple class:
    Code:
    class Koala
    {
    
    public:
    
      Koala();
      Koala(const char* name);
      ~Koala();
      Koala&        GetPartner();
      void          KillPartner();
    
    private:
    
      const char*   _name;
      Koala*        _partner;
      bool          _hasPartner;
    
    };
    Here is one of the methods:

    Code:
    void            Koala::KillPartner()
    {
      Koala         *tmp;
    
      if (this->_hasPartner == true)
        {
          tmp = &(this->GetPartner());  // So I have his next partner which is another instance of the object.
          //And here I can access all of his private variables...
          delete tmp;
        }
    }
    Now I am able to access ALL the private variables, of all my different instances of the object. (Koala A; Koala B; And Koala B can access private variables of Koala A as long as I have a pointer to the object).

    I compile like this: "g++ -W -Wall *.cpp".

    So my question.. How come it works? Arent Private/Protected variables supposed to be protected from each other? Or are all private variables, private between all the instances of the same object.

    Thank you guys!

  2. #2
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    Quote Originally Posted by +Azazel+ View Post
    Or are all private variables, private between all the instances of the same object.
    Yes, rather, a class can access any protection level (public, protected, private) of any of it's own instances (aside from a possible detail someone's going to correct me about from the standard's sections). Basically an implicit friendship, why wouldn't you be friends with yourself?

    If this weren't the case, I would pull my hair out writing copy constructors.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  3. #3
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    838
    if private variables were private to a particular instance of a class, and not just within the scope of the class, copy construction and assignment would be impossible.

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Also, the point of private members is code encapsulation. It's about separating code, not instances. It allows separate development of the internal object implementation and the external use (ideally). Having a class member access the implementation details of another instance of itself does not hinder this separate development.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It seems logical that a class can access the internals of an external instance of a class of the same type as the class itself, because otherwise implementing a lot operators (like operator =, etc) would be impossible (or very messy), since the class would need to access the external instance's internals.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    As a side note suggestion, I'd advise for you to review your variable naming convention for private members of a class. I too use a specific convention for private members. I find terrifically useful while designing my classes and their relationships , since I can identify a private member at a glance.

    In your case you are opting for starting the identifier with an underscore. Nothing wrong with this. But besides identifiers starting with a double underscore, the standard also reserves identifiers that start with an underscore followed by a uppercase letter.

    While you aren't breaking this, you get close to it and identifiers like

    Code:
    _longitude //ok
    _Longitude // potential problem. Reserved.
    become less obvious to the eye (where the convention you may choose is more important). It's not a big deal, anyway. But I'd suggest something a little different. For instance moving the underscore to the end of the identifier. So,

    Code:
    const char*   name_;
    Koala*        partner_;
    bool          hasPartner_;
    This is what I do personally. But it's not my intention to have you do as I do. Simply to point out what I believe is a small problem in your convention.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I like the prefix m_.
    const char* m_name;
    Koala* m_partner;
    bool m_hasPartner;
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    I don't prefix or suffix my C++ code. Just like most people don't in scripting languages. I find it more aesthetically pleasing and easy to read (and I always explicitly use the 'this' variable so I don't need to prefix member variables), IDE's help with this, and I never use reserved names anyway. Although when I do use a prefix/suffix, I use an underscore suffix like Mario F, mostly because that seems to be well adopted by Boost (Asio specifically). I used to use m_, and even mb_, mi32_ and other verbose names, merely because I read it in a book (which I then read was stupid if you ended up changing the type).

    That's just me. Haven't had a problem yet.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Yes, rather, a class can access any protection level (public, protected, private) of any of it's own instances (aside from a possible detail someone's going to correct me about from the standard's sections). Basically an implicit friendship, why wouldn't you be friends with yourself?

    If this weren't the case, I would pull my hair out writing copy constructors.
    I still shiver a bit when a copy constructor or something accesses another class's private members. I much prefer to use protected functions or something to do the same job . . . though whether that actually makes the code any easier to maintain and whatnot is something I haven't figured out. Just a personal opinion.

    [Okay, I give. What's the possible little detail?]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    If it was not possible for one instance to access the private members of another instance it would actually hurt encapsulation. The class would have to expose accessors to allow access to the internal state (for copy construction and other useful things), but then these accessors would be available in general and other code could then use them to access internal state it has no reason to access.

    The alternative would be to declare the class to be a friend of itself, which seems really weird.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  11. #11
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    I didn't suggest using public accessors . . . I suggested (at least I hope I did) that one use protected accessors. That way, private data is only used inside a class itself, and if it wants to access data from another instance of itself, it has to go through the protected interface. As I mentioned, it's just a personal opinion, one which will probably disappear the moment I try to code a sticky situation which the abovementioned private access would make much easier.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by dwks
    I didn't suggest using public accessors . . . I suggested (at least I hope I did) that one use protected accessors. That way, private data is only used inside a class itself, and if it wants to access data from another instance of itself, it has to go through the protected interface.
    Why protected instead of private? After all, this is merely a convention, but making them protected means that subclasses can access them when they perhaps should not.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Yes, of course. Really, there should perhaps be another access level for "other instances of the same class, or subclasses thereof" (as if C++ needs another access level . . .).

    I guess it's another side of the old argument: should a class access its private variables directly, or through accessor methods? Because the protected methods I mentioned could easily be private ones . . . in which case it's a question of whether that makes the code any easier to use.

    You wouldn't happen to know what the "possible detail" is, would you?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by dwks
    You wouldn't happen to know what the "possible detail" is, would you?
    It is possible that it does not exist, or that Dae had something in mind that is not implied, and merely wanted to "protect" himself/herself pre-emptively.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    Quote Originally Posted by laserlight View Post
    merely wanted to "protect" himself/herself pre-emptively.
    Haha, yup that's it. As the first response I always feel like someone's going to come up behind and me and quote some random part of the standard ("actually Dae is wrong because section 3.2.9 says this and that"). I'd like to at least imply I don't know exactly what I'm talking about, so I don't warp the OP. I haven't read barely any of the standard, and haven't followed a book in a long time. Been meaning to get around to that.

    Quote Originally Posted by dwks View Post
    Yes, of course. Really, there should perhaps be another access level for "other instances of the same class, or subclasses thereof" (as if C++ needs another access level . . .).
    How about a modifier, haha? Could always use more of those. o.o
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. benefits of private or protected constructor
    By George2 in forum C++ Programming
    Replies: 1
    Last Post: 11-03-2007, 01:02 AM
  2. How can I reach Protected Variables?
    By zayzay in forum C++ Programming
    Replies: 8
    Last Post: 07-14-2005, 06:32 AM
  3. Declaring an variable number of variables
    By Decrypt in forum C++ Programming
    Replies: 8
    Last Post: 02-27-2005, 04:46 PM
  4. member access and inheritance
    By Laserve in forum C++ Programming
    Replies: 3
    Last Post: 08-27-2004, 04:09 PM
  5. Replies: 6
    Last Post: 01-02-2004, 01:01 PM