In C++, the private access specifier restricts access to class members, making them accessible only within the class. This ensures data security and encapsulation, preventing direct modification from outside the class.
1️⃣ Syntax of private Access Specifier
class ClassName {
private:
// Private members (accessible only inside the class)
int data;
void privateFunction() {
cout << "This is a private function." << endl;
}
};
2️⃣ Example: Private Members in a Class
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance; // Private variable
public:
void setBalance(double b) { // Public method to modify balance
if (b >= 0)
balance = b;
}
double getBalance() { // Public method to access balance
return balance;
}
};
int main() {
BankAccount account;
// account.balance = 1000; // ❌ Error: Cannot access private member
account.setBalance(1000); // ✅ Allowed via public function
cout << "Balance: $" << account.getBalance() << endl;
return 0;
}
Output:
Balance: $1000
Explanation:
Direct access to balance is not allowed because it's private.
setBalance() and getBalance() act as getter and setter functions to modify and retrieve the value safely.
3️⃣ Key Characteristics of private Access Specifier
4️⃣ Private Access in Inheritance
When a class is inherited, private members do not become accessible in the child class, but they still exist in the memory.
Example: Private Members Are Not Inherited
#include <iostream>
using namespace std;
class Parent {
private:
int secret = 42; // Private member
public:
int getSecret() { // Public function to access private member
return secret;
}
};
class Child : public Parent {
// secret is not accessible here
};
int main() {
Child obj;
// cout << obj.secret; // ❌ Error: Private member is inaccessible
cout << "Secret: " << obj.getSecret() << endl; // ✅ Accessed via public function
return 0;
}
Output:
Secret: 42
Explanation:
secret is private in Parent, so it cannot be accessed in Child.
getSecret() provides controlled access to secret.
5️⃣ When to Use private Access Specifier?
✅ To protect sensitive data from direct modification.
✅ To enforce encapsulation, allowing access only through controlled methods.
✅ When implementing internal helper functions that should not be exposed.
6️⃣ Comparison of Access Specifiers
Would you like to see protected access specifier next? 🚀
0 Comments