When using C ++, access to a private attribute inside the main function is not allowed. Example:
#include <iostream>
using namespace std;
class Test {
private: int a;
public:
Test(int value) { a = value; }
int getValue() { return a; }
};
int main (int argc, char *argv[]) {
Test test2(4);
cout << test2.a;
cout << test2.getValue();
return 0;
}
It is clear why an error occurs when accessing private attributes outside the class methods, since C ++ does not have basic functions inside classes.
However, in Java it is allowed:
public class Test {
private int a;
public Test(int value) { a = value; }
public int getValue() { return a; }
public static void main (String args[]) {
Test test1 = new Test(4);
System.out.println(test1.a);
}
}
I understand that in this case, main is INSIDE for the Test class. However, I cannot understand the idea of why this is allowed, and what is the impact of this on code development / management.
When I learn C ++, I once heard: "Classes should not have a main one. The main action is with or uses class instances."
Can someone shed light on this issue?
source
share