0

What's the difference between a private variable in a Java class and a private variable in a C++ structure?

Java code for example see below : implementing an ADT table. c++ example see below : applying "hiding the implementation"

I looked online couldn't find any helpful source related to this particular topic

Java example:

class Table{
    private int size;
    private int num;//numbers of items are stored in the arrray
    private int[] array;

    public Table(int size, int[] array){
        this.size = size;
        this.array = new int[size];
    }

    public insert(int[] array, int newItem){
        if(num<size){
            //for loop for adding items into the array;
        }
        else if(num>=size){
            //increment the size and copy the original array to the new array
        }
    }
}

C++ example of implementation hiding:

struct B{
private:
    char j;
    float f;

public:
    int i;
    void func();
};


void::func(){
    i = 0;
    j = '0';
    f = 0.0;
};

int main(){
    B b;
    b.i = i; // legal
    b.j = '1'; // illegal
    b.f = 1.0; // illegal now

}

in c++ we cant change the private variable, is it because these b.j = '1'; b.f = 1.0; two lines are in the main() function thats why? in java we cant change the private variables in main() neither.

thank you!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065

2 Answers2

5

With very few exceptions, private variables in C++ and Java work similarly. Specifically, in general, those variables can only be accessed by member functions of the class or struct containing those variables. Access to those fields / data members is otherwise disallowed.

There are a couple of exceptions to this rule. A non-exhaustive list:

  • In Java, you can use reflection to make private fields of other classes accessible, though doing so may be prevented by the access controller.

  • In C++, private fields may be accessed by classes and functions that are marked as friends of the class containing the private field.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

Private variables are variables that are NOT accessible outside of the class itself.

Learn more about access modifiers here

C++ private in structs are similar, in the way that they can only be accessed in the struct's member methods.

EDToaster
  • 3,160
  • 3
  • 16
  • 25