Thread: Public vs. Private variables in classes

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Advanced Novice linucksrox's Avatar
    Join Date
    Apr 2004
    Location
    Michigan
    Posts
    198
    or of course you could always return a pointer to the private variable... but as of yet i'm still unsure why that is useful. but it just is... that's all i know
    "What are all you parallelograms doing here?" - Peter Griffin (to Joe and his wheelchair buddies)

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    125
    Everything public on a class is called the interface. This is the stuff you can use to order the class to do things. Generally you want the interface of a class to be as small as possible, and this also means variables you don't NEED to change from outside of the class shouldn't be part of the interface.
    If a variable IS in fact part of the interface, it's still better to make it private and have a function to read it and a function to change it because this way you can prevent your user from setting the variable to something that doesn't make sense.
    Imagine an amplifier with a configurable volume that's a float between zero and ten. If you just leave the variable part of the interface there's nothing that prevents the user from setting the volume to 11, 259268 or -3, even though those values might cause severe trouble later on. Having the variable private with a Get and Set function would allow you to automatically limit the values of the variable.

    Mostly though, making stuff private is just convenient for the same reason minimising the amount of global variables and functions is convenient: if your project gets large it's very practical that you don't have to know what variables should be changeable and which aren't. (like what Dante Shamest posted)
    Typing stuff in Code::Blocks 8.02, compiling stuff with MinGW 3.4.5.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. about private class variables
    By bulletbutter in forum C++ Programming
    Replies: 5
    Last Post: 04-18-2008, 12:13 PM
  2. #define private public
    By revelation437 in forum C++ Programming
    Replies: 21
    Last Post: 12-20-2003, 04:37 PM
  3. I need a code for Tic Tac Toe game ?
    By martyr in forum C++ Programming
    Replies: 11
    Last Post: 12-07-2003, 03:29 AM
  4. Exporting Object Hierarchies from a DLL
    By andy668 in forum C++ Programming
    Replies: 0
    Last Post: 10-20-2001, 01:26 PM