Thread: Do I always need to use member functions in a class to access class variables?

  1. #1
    Registered User
    Join Date
    Jul 2017
    Posts
    8

    Do I always need to use member functions in a class to access class variables?

    Just tell me the general idea, I need to clarify and understand it without extra details.

    In a class you usually create variables and functions. And tutorials say you should make your class variables private and set/get their values using class member functions. When is it ok to access class variables directly?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > When is it ok to access class variables directly?
    Probably never - but as with all things programming, exceptions to the rule are possible, and may even be preferred.

    Your average 1-liner set/get is going to be implemented very efficiently anyway, so you should do this by default.

    Plus if your set/get ever needs to become something else, the change to the internal implementation only has to be done in one place.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jul 2017
    Posts
    8
    Ok, thanks. May I ask a few questions about classes? I'm making a game project and kind of confused about access modifiers for classes.
    Last edited by UltimateGames; 08-01-2017 at 05:09 AM.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Just ask away.
    Someone will answer if they feel willing and able.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Jul 2017
    Posts
    8
    I'll think, maybe in another thread.

  6. #6
    Registered User
    Join Date
    Jul 2017
    Posts
    8

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 11-18-2012, 11:17 AM
  2. Can Nested class access parent class's private member?
    By meili100 in forum C++ Programming
    Replies: 4
    Last Post: 06-05-2009, 08:42 AM
  3. Replies: 25
    Last Post: 10-29-2007, 04:08 PM
  4. derived class can not access base class protected member?
    By George2 in forum C++ Programming
    Replies: 2
    Last Post: 10-21-2007, 06:32 PM
  5. Class member variables only readable by member functions?
    By _Elixia_ in forum C++ Programming
    Replies: 4
    Last Post: 10-10-2003, 03:52 PM

Tags for this Thread