laxman digari
laxman digari

Reputation: 127

Private member in a class

What is main purpose of declaring members as private in a class? As far as I know, we cannot access private members from outside of the class.

Upvotes: 0

Views: 94

Answers (3)

sellmeadog
sellmeadog

Reputation: 7517

Most C-style languages will typically provide you public, protected, and private access modifiers. This allows you to build your classes and class hierarchies and expose members on a "need to know" basis, i.e., "what mama don't know won't hurt her."

That is exactly what private access is for. If no one else needs to know about the existence of a class member, make it private and increase accessibility only as needed.

Upvotes: 0

griegs
griegs

Reputation: 22770

The point is that you don't want to expose them to the outside world. Marking them as such makes them more readable too.

eg:

public string name {get;set;}
public string emaul {get;set;}

private bool saved {get;set;}

rather than;

public string name {get;set;}
public string emaul {get;set;}

bool saved {get;set;}

Just a little easier to read.

Upvotes: 2

Waqas
Waqas

Reputation: 6812

Yes, this is the main purpose of private so that class members can't be accessible outside class. This is known as data hiding in OOP and the main purpose of this is to give owner of class ability to hide data or function so that they can only be used by functions inside class only.

Upvotes: 0

Related Questions