public members can be accessed from outside the class they were declared in, private members can only be accessed from within the class they were declared in. Private members are commonly manipulated through get/set methods, which allows for greater encapsulation and hides the implementation from the calling function.
Example:
class sampleClass{
private: int private_member;
public: int public_member;
public: void setPrivateMember(int x){private_member = x;}; // private members can be accessed from within the class that they are declared in
public: int getPrivateMember(){return private_member;};
};
int main()
{
sampleClass A;
A.public_member = 5; // Perfectly legal
A.private_member = 7; // Syntax error, this will not compile
A.setPrivateMember(7); // Legal
cout << A.getPrivateMember(); // Legal
return 0;
}
Copyright © 2026 eLLeNow.com All Rights Reserved.