Public Data
Concept Definition
Public data means outside code can directly read and write an object's internal state. That may look convenient, but it removes the class's ability to protect its rules. A class with public state often becomes a simple bag of variables instead of a responsible object.
A useful analogy is a bank vault with the door left open. Anyone can change the contents, so the bank cannot guarantee correctness.
Why It Matters
OOP is built around state plus behavior. If every field is public, behavior can be bypassed. For example, a BankAccount can no longer guarantee that balance never becomes negative.
Encapsulation is not decoration. It centralizes validation and keeps object invariants safe. An invariant is a rule that should always remain true for a valid object.
Syntax Block
class Account {
private:
double balance = 0.0; // protected state
public:
bool withdraw(double amount); // controlled behavior
};
Explained Code
Example: Protecting Balance
class Account {
private:
double balance = 0.0; // invariant: balance is not negative
public:
explicit Account(double openingBalance) : balance(openingBalance) {} // initialize
bool withdraw(double amount) {
if (amount <= 0.0 || amount > balance) { // validate request
return false; // reject invalid change
}
balance -= amount; // preserve invariant
return true; // report success
}
double getBalance() const { return balance; } // read-only access
};
Outside code can ask for a withdrawal, but it cannot directly assign balance = -999.
Key Points / Rules
- Keep data private by default.
- Expose behavior that preserves invariants.
- Use getters only when outside code truly needs read access.
- Use setters carefully and validate inputs.
- Public constants can be acceptable; public mutable state is the main risk.
Common Mistakes
- Making data public to avoid writing methods. Convenience now creates bugs later.
- Adding setters that accept anything. A setter without validation may still break invariants.
- Returning non-const references to private data. That can leak write access.
- Thinking encapsulation means hiding everything. Encapsulation means exposing safe operations.
Quick Check
- What invalid state can public
balancecreate? - Why is
withdraw()better than direct balance assignment?
Viva Answer
Public data is dangerous because outside code can break object invariants. Private data plus validated public behavior keeps state controlled.