Announcement

Collapse
No announcement yet.

What is the point in using private and protected variables in C++?

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

    What is the point in using private and protected variables in C++?

    I just don't see the point. Seems like their purpose is explicitly to create hassle for people. Public variables aren't global, they still require a pointer reference of the particular object/class that has that variable.

    I can never know whether I will need one class/object to know data of a particular variable from another. And usually I DO, so I just tend to declare all variables as public.

    #2
    The concept of object oriented programming uses the term encapsulation where you have related data together and accessible by a common meaning. Global variables are a concept that usually increases cost of maintainability of software because one can never know where in a system all the places a global variable can be changed, and even thou you can change a public variable in the scope of a class, it is not recommended doing so, so they are usually used as the meaning of properties of the object as describing it and not being a value which depends on a certain algorithm to change its contents.

    Private variables in the scope of a class means that only the class can change its values and any other class derived (inheritance) from the first won't be able to access it, meaning you won't have again problems on finding which piece of code is modifying that variable.

    Protected variables in the scope of a class means that derived classes (again inheritance) can change the variable and this is useful is a derived class usually has a better algorithm to change the value, so you can have better code implemented on top of old code and this avoids that you change the original code and breaks compatibility with other pieces of software that uses it.

    These are all well documented in Computer Science papers and the concepts were created even before the man landed on the Moon. It is present in several languages, just to mention a few: C#, Java, among several others, includes experience from creating very large systems, with hundreds of million lines of code.
    Nilson Lima
    Technical Director @ Rigel Studios Ltda - twitter: @RigelStudios
    Join us at Discord: https://discord.gg/uFFSEXY

    UE4 Marketplace: Cloudscape Seasons
    supporting: Community FREE Ocean plugin

    Comment


      #3
      Thanks, I read the definitions, that still doesn't give me a good explanation for why I would ever want to use private and protected variables under any circumstances.

      Private mentioned the "finding" as its reason of existence, but today, you have the glorious feature called Ctrl + F, also known as search, so that makes the point redundant. Widely used for browsers and code editing programs.

      Protected mentions an odd use, and it's to "maintain compatibility". Seems legit, but when you require to know the information or change it externally for whatever reason, this would create a barrier. The thing to do then would be to make the variable public but you probably can't or shouldn't.

      I need to have a good reason to use them, and the answer seems to be exactly what I saw as the problem; to create hassle. Seems like a terrible thing to do.

      Comment


        #4
        Originally posted by L11777 View Post
        Thanks, I read the definitions, that still doesn't give me a good explanation for why I would ever want to use private and protected variables under any circumstances.

        Private mentioned the "finding" as its reason of existence, but today, you have the glorious feature called Ctrl + F, also known as search, so that makes the point redundant. Widely used for browsers and code editing programs.

        Protected mentions an odd use, and it's to "maintain compatibility". Seems legit, but when you require to know the information or change it externally for whatever reason, this would create a barrier. The thing to do then would be to make the variable public but you probably can't or shouldn't.

        I need to have a good reason to use them, and the answer seems to be exactly what I saw as the problem; to create hassle. Seems like a terrible thing to do.
        The only thing I can say is that you need to read something from the source, like a book from the C++ creator and some object oriented programming concepts. These will be all clarified. Remember, C++ is also a industry standard and many science areas use it to create software, just happens it fits 3D tools aswel. Every resourceful engine out there is written in C++ at its core, even Unity is.
        Nilson Lima
        Technical Director @ Rigel Studios Ltda - twitter: @RigelStudios
        Join us at Discord: https://discord.gg/uFFSEXY

        UE4 Marketplace: Cloudscape Seasons
        supporting: Community FREE Ocean plugin

        Comment


          #5
          Often times, when writing code, you are writing APIs or a set of objects / tools for yourself and other engineers to build upon. Public / Private / Protected are contracts between you and future programmers on how to interface with your code. Private variables cannot be touched (unless you expose methods to get/set them), Protected can be overwritten if you wish by child classes, and Public are the wild west.

          Same with const correctness (let's pretend const_cast doesn't exist because, seriously, don't use it). A member / method that is marked as const tells any future programmers that you may call that function without worrying it will modify the object in some way, where non-const methods say the opposite.

          Can you write everything with only Public members? Sure. Is it good practice? Definitely not.

          Able Ability System - A high performance, robust ability system for UE4. Now Available!

          Comment


            #6
            Writing code is the easy part. Reading code and understanding the intent of the programmers who wrote it takes most of the time. Like already mentioned you could easily make everything public and don't look back but it won't give the reader any nuances while they read the code.

            Comment


              #7
              The use I have found for private variables is say you have a health variable. But you want to have a function be called each time you set the health(like for example a visual update). So what I did in that case was make my health variable private and made Get and Set functions for that variable. In the Set function it sets the health variable and calls any other function I want to be called with it. Making it private forces any other programmer to use those 2 functions so when updating the health value that additional function is called.

              Comment


                #8
                Originally posted by Mootjuh View Post
                The use I have found for private variables is say you have a health variable. But you want to have a function be called each time you set the health(like for example a visual update). So what I did in that case was make my health variable private and made Get and Set functions for that variable. In the Set function it sets the health variable and calls any other function I want to be called with it. Making it private forces any other programmer to use those 2 functions so when updating the health value that additional function is called.
                This design principle is built into C# under the name "Property" so yes it is very useful.
                Last edited by GarnerP57; 02-19-2019, 11:54 AM.

                Comment


                  #9
                  For the sake of discussion, let's just consider private and protected variables to be the same thing. We use them to protect the state of an object from outside interference.

                  Let's consider a class that we use every day. TArray. TArray has protected variables that look something like this:
                  Code:
                  uint8 * Data; // a pointer to a chunk of memory for the objects in the array
                  int32 ArrayNum; // the number of objects in the array
                  int32 ArrayMax; // the maximum number of objects that Data chunk of memory can hold, when ArrayNum is bigger than ArrayMax, we need to allocate a bigger chunk of memory to Data.
                  You could fairly easily make these variables public, and just access Data directly. When you insert a new object, you increment ArrayNum, when you delete, you decrement ArrayNum.

                  Now, imagine you have a new programmer on your team, they add 1000 objects to the array, correctly incrementing ArrayNum. But they are so noob that they forget to check if ArrayNum is bigger than ArrayMax and allocate new memory for the huge number of objects. Crash.

                  Wouldn't it be easier if you hid these variables from that noob and made sure they used functions like Add that always check when ArrayNum is larger than ArrayMax?

                  So, the purpose of protected and private, is to hide implementation details from other programmers. It makes code less error prone and safe from programmer mistakes.

                  When you write a really big code project, with 100,000 lines of code, the noob programmer sometimes becomes yourself. It is difficult for my feeble little mind to remember the details of code that I wrote 5 years ago, so I have to protect myself from myself, with protected variables.

                  Comment

                  Working...
                  X