What is a data encapsulation?
Data Encapsulation : The wrapping up of data and functions into a single unit (Class) is known as Encapsulation. By encapsulating the data inside the class; data is not accessible to the outside world. Only those functions which are wrapped inside the class can access it. This provides protection to the data since access to it is controlled. Objects of the class can thus access the data only using the methods provided by the class.
Class MyClass
{
int roll, marks;
public:
{
int getmarks()
{
return marks;
}
}
};
int main()
{
MyClass s;
int m;
m = s.getmarks;
}
- As seen above, the class MyClass has two data members viz. roll and marks. These members can not be accessed directly from outside the class i.e. they are encapsulated inside the class. To access them, we need to create object of that class and invoke the data accessing function (‘getmarks’ in this case) using that object.