The Student Room Group

Private Class in Object Oriented [Comp 3]

So, I don't really understand this. The private class apparently makes the variables it holds unavailable to the program. So to secure itself.

But whats the point? When you supply your program to a consumer, they dont have the code anyways, so how can the access the private variables? Even if u set it as public, they cant get to it because of information hiding right?

Well, can someone just explain it to me.

Thanks
Reply 1
Aren't you supposed to use the methods? (my course doesn't involve any details of object orientated programming).
Reply 3
2710
So, I don't really understand this. The private class apparently makes the variables it holds unavailable to the program. So to secure itself.

But whats the point? When you supply your program to a consumer, they dont have the code anyways, so how can the access the private variables? Even if u set it as public, they cant get to it because of information hiding right?

Well, can someone just explain it to me.

Thanks


Things are set private to prevent other programmers from modifying them directly. If you want your code to be reusable (which is one of the main purposes of object oriented programming) then you will have things like data integrity checks in methods which set the values, to ensure that a value that cannot physically fit into the variable cannot be abused and used to inject malicious code or cause other side effects.

Mutators and Accessors are one design choice which can be made when a class requires some form of direct modification to the variables, however it is possible that some will never be referenced by anything other than the methods of the class itself for example I could write a class using C++ to represent a stack of integers:
class Stack
{
private:
int array[10];
int top;
public:
Stack();
~Stack();
bool Push(int num);
int Pop();
void Display();
};


In the context of this class, the only things that need to reference the array or top variables are the methods themselves. This means I can also prevent a programmer for setting the top as 12 which upon attempting to Pop() the value from the top would result in a memory access violation.

Latest

Trending

Trending