C++ Access Modifiers
C++ access modifiers (public, private, protected) control the visibility of class members.
C++ में access modifiers (public, private, protected) क्लास के मेम्बर्स की विजिबिलिटी कंट्रोल करते हैं।
Example 1: Public Members
#include <iostream>
using namespace std;
class Employee {
public:
string name;
int age;
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Employee emp;
emp.name = "John";
emp.age = 30;
emp.display();
return 0;
}
Output:
Name: John, Age: 30
Public members can be accessed directly outside the class.
Public मेम्बर्स को क्लास के बाहर डायरेक्ट एक्सेस कर सकते हैं।
Example 2: Private Members
#include <iostream>
using namespace std;
class Employee {
private:
int salary;
public:
void setSalary(int s) {
salary = s;
}
void displaySalary() {
cout << "Salary: " << salary << endl;
}
};
int main() {
Employee emp;
emp.setSalary(50000);
emp.displaySalary();
return 0;
}
Output:
Salary: 50000
Private members are accessed via public methods.
Private मेम्बर्स को public मेथड्स से एक्सेस करते हैं।
Example 3: Protected Members with Inheritance
#include <iostream>
using namespace std;
class Employee {
protected:
int id;
};
class Manager : public Employee {
public:
void setId(int i) {
id = i;
}
void showId() {
cout << "Manager ID: " << id << endl;
}
};
int main() {
Manager m;
m.setId(101);
m.showId();
return 0;
}
Output:
Manager ID: 101
Protected members are accessible in derived classes.
Protected मेम्बर्स derived क्लास में एक्सेस कर सकते हैं।
Example 4: Mixed Access Specifiers
#include <iostream>
using namespace std;
class Employee {
public:
string name;
private:
int age;
protected:
int salary;
public:
void setData(string n, int a, int s) {
name = n;
age = a;
salary = s;
}
void showData() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
Employee emp;
emp.setData("Alice", 28, 60000);
emp.showData();
return 0;
}
Output:
Name: Alice Age: 28 Salary: 60000
Shows public, private, and protected members usage together.
Public, private और protected मेम्बर्स का एक साथ उपयोग।