Access Modifier
Access Modifier
Data hiding is one of the important features in Object Oriented Programming which functioning as the access restriction of a program to access directly to internal representation class type. These access restriction are called as access modifier, which included:1.) Public 2.) Private 3.) Protected Public A public member is accessible from anywhere outside the class but within the program. Example: class Result{ public: double marks; int attendance; void CalculateMarks(); }; int main(){ Result student1; student.marks = 62.5; cout<< Marks of student1 is ; << student1.marks<<endl; return 0; } In above example, the variable of marks, attendance, and function CalculateMarks is able access from anyone outside of the class. Due to marks is accessible from anyone, so marks is setted as 62.5 for new object student1.
Private A private member variable or function cannot be accessed or viewed from outside the class. If the programmer never give the access modifier to the function or attributes, the compiler will assume that it is a private field. Example: class Result{ public: double marks; private: int attendance; void CalculateMarks(); }; int main(){ Result student1; student1.marks = 70.5; //this is working because its public varible student1.attendance= 70; //having error, because its private field return 0; } In above example, all the variable or function is not accessible from outside class, only the class and friend function can use the private members.
Protected A protected member variable and function is similar with private access modifier but it have one extra features which is they can be accessed in child class which also called as derrived class. Example: class Result{ public: double marks; protected: int attendance; }; class testResult:Result { public: void CalculateMarks( double testmark); }; int main(){ testResult student1; student1.CalculateMarks(56.5); return 0; }