Access modifiers belong to the Apex language, so the question is really about Apex, the programming language that runs on the Salesforce platform. Apex has four of them: public, private, protected and global. The first three work much as they do in C++. global is the widest level, used when code in other namespaces needs to call in.
The four Apex access modifiers
privatemembers are visible only inside the class that declares them. Members without a modifier are private.protectedmembers are visible inside the class and its subclasses.publicmembers are visible to Apex code in the same namespace.globalmembers are visible to all Apex code, including code in other namespaces, such as an installed managed package.
A small example
public class Counter {
private Integer total = 0;
public void add(Integer amount) {
total += amount;
}
public Integer getTotal() {
return total;
}
}
Other classes cannot change total directly. They have to call add, which keeps the rule in one place. This is the same idea as Encapsulation in C++, applied to Apex.
Why global needs care
Other code may depend on a global member, so changing or removing one can break code outside your own namespace. Prefer public unless a managed package has to expose the member.
with sharing is not an access modifier
You will see with sharing and without sharing on class declarations, such as public with sharing class Counter. They control whether the class respects the running user’s record sharing rules. They do not decide which code can call the class’s members.
Comparing with C++ and Java
private, protected and public in Apex follow the same ideas as in Access Modifiers in C++. Apex’s default for members without a modifier is private, while Java’s default is package-level access, covered in What Are Access Modifiers in Java? C++ and Java have no direct equivalent of global, which is specific to Apex’s namespace model.