Thread: Private or Public

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    16

    Private or Public

    Hi, I was curious why you would neet to declare and variable in a class as private, and then use the get and set for the property, when you could just use a public variable? I might be getting something confused and need just a bit more explanation.

    Thanks

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    You can do it to maintain a proper state of the object.

    Lets say you had an object that contained two integers. One of which can never be lower then 2. Well if you just had a public variable then anyone could assign a value of 1 to it. However if you make them go through one of your functions to change it then you can check first to make sure its a proper value.

  3. #3
    Registered User Frobozz's Avatar
    Join Date
    Dec 2002
    Posts
    546
    Concerning what Thantos said, it also makes it so the programmer using your object does not have to check to see if the value going into it is less than 2. This makes it easier on the programmer later when he has to debug the program.

  4. #4
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Location
    Australia
    Posts
    986
    And even if you don't want to check if it's less than two, it's best to do it anyway, because one day you might like to. For example, in all of my properties that return a string, I check if the string is null and return string.Empty rather than null.

    It's just good practice. One of the great goals of object oriented programming is encapsulation. Exposing your private parts to strangers isn't recommended

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. Linking problems in Visual Studio
    By h3ro in forum C++ Programming
    Replies: 5
    Last Post: 03-04-2008, 02:39 PM
  3. Need help with calculator program
    By Kate in forum C# Programming
    Replies: 1
    Last Post: 01-16-2004, 10:48 AM
  4. 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
  5. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM