What is visibility modifier ? List out them with example
In : BCA Subject : OOPS and Data StructuresIn C++, visibility modifiers control how class members (variables and functions) can be accessed from outside the class or from derived classes.
public - Anyone (inside & outside the class)
private - Only inside the class
protected - Inside the class and derived classes
Example :
#include <iostream>
using namespace std;
class MyClass {
public:
int publicVar; // Accessible anywhere
private:
int privateVar; // Only accessible inside this class
protected:
int protectedVar; // Accessible inside this class and child classes
};
int main() {
MyClass obj;
// Public variable - Allowed
obj.publicVar = 10;
cout << "Public Variable: " << obj.publicVar << endl;
// Private variable - Not allowed (will give error if uncommented)
// obj.privateVar = 20;
// Protected variable - Not allowed (will also give error)
// obj.protectedVar = 30;
return 0;
}