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:
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.