These are the notes for C++ episode 14. In episode 13 our Account learned to start correct (constructors) and clean up after itself (destructors). Today we make sure nobody outside can break it. You will see why main can't read a private member, what goes wrong when you make the data public, and then invent the fixes one by one: getters (a read-only window), const member functions (a promise not to change the object), actions with rules instead of plain setters, and the idea that ties them together, encapsulation. On the way you'll meet the default access of class vs struct, the third label protected (family only), and see the real payoff: changing a class's insides without touching a single line of main. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.
What is an access specifier?
An access specifier is a label inside a class that says who may use the members written after it. C++ has three:
| Label | Who can use the members after it |
|---|---|
private: |
only the class's own member functions |
protected: |
the class's own functions and the functions of classes derived from it |
public: |
everyone, including main |
A label stays in force until the next label. In a class, everything before the first label is private.
The problem: locked out of our own data
Here is our account from episode 13. owner and balance sit above public:, so they are private. deposit() only accepts positive amounts. main just wants to print the balance.
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
Account(string n, double b) : owner(n), balance(b) {}
void deposit(double amt) { if (amt > 0) balance += amt; }
};
int main() {
Account a("Ravi", 5000);
a.deposit(1000);
cout << a.balance << endl;
return 0;
}
g++ says:
error: 'double Account::balance' is private within this context
Why it failed: private means only the class's own functions may touch the member. main is outside the class, so it can't even read balance. ("Within this context" means "here, in main".)
The obvious fix, and the public disaster
The obvious fix is to move public: up, so everything is public. Now main can read the balance. But look at what else it can do:
#include <iostream>
#include <string>
using namespace std;
class Account {
public:
string owner;
double balance;
Account(string n, double b) : owner(n), balance(b) {}
void deposit(double amt) { if (amt > 0) balance += amt; }
};
int main() {
Account a("Ravi", 5000);
a.deposit(-200);
a.balance = -90000;
cout << a.owner << ": " << a.balance << endl;
return 0;
}
Output:
Ravi: -90000
deposit(-200) was refused by its check, but the next line skipped deposit completely and wrote -90000 straight into balance. It compiled with no warning.
Why it failed: public data can be changed by anyone, to anything. The check inside deposit protected nothing, because nobody is forced to go through deposit.
Getters: the bank passbook
Real-life example: a bank passbook.
| At the bank | In C++ |
|---|---|
| You can read your balance in the passbook printout any time | a getter, getBalance() const: read-only access |
| You can't write a new balance in it with a pen | the data stays private: no direct writes |
| Money only changes at the counter, where the cashier checks first | actions with rules: deposit(), withdraw() |
A getter is a public member function that simply returns a private value. The data stays private; the getter is a read-only window on it.
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
Account(string n, double b) : owner(n), balance(b) {}
double getBalance() const { return balance; }
void deposit(double amt) { if (amt > 0) balance += amt; }
};
int main() {
Account a("Ravi", 5000);
a.deposit(1000);
cout << a.getBalance() << endl;
a.balance = -90000;
return 0;
}
g++ says:
error: 'double Account::balance' is private within this context
Writing is blocked, exactly as we want. Delete that line:
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
Account(string n, double b) : owner(n), balance(b) {}
double getBalance() const { return balance; }
void deposit(double amt) { if (amt > 0) balance += amt; }
};
int main() {
Account a("Ravi", 5000);
a.deposit(1000);
cout << a.getBalance() << endl;
return 0;
}
Output:
6000
Reading works through the getter; changing goes only through deposit, which checks.
const member functions: the promise
Why is there a const after getBalance()? Here's the getter without it, and a function printSlip that takes a const Account& (episode 10: a reference that promises not to change the account):
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
Account(string n, double b) : owner(n), balance(b) {}
double getBalance() { return balance; }
void deposit(double amt) { if (amt > 0) balance += amt; }
};
void printSlip(const Account& acc) {
cout << "Balance: " << acc.getBalance() << endl;
}
int main() {
Account a("Ravi", 5000);
printSlip(a);
return 0;
}
g++ says:
error: passing 'const Account' as 'this' argument discards qualifiers [-fpermissive]
Why it failed: inside a member function, this points to the object it was called on. The account here is const, and C++ doesn't know whether getBalance() changes it. With no promise, it refuses the call: calling it would "discard" the const qualifier.
Add const after the brackets. That is the promise: this function only reads.
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
Account(string n, double b) : owner(n), balance(b) {}
double getBalance() const { return balance; }
void deposit(double amt) { if (amt > 0) balance += amt; }
};
void printSlip(const Account& acc) {
cout << "Balance: " << acc.getBalance() << endl;
}
int main() {
Account a("Ravi", 5000);
printSlip(a);
return 0;
}
Output:
Balance: 5000
The compiler holds the function to its promise. If a const member function tries to change a member:
#include <iostream>
#include <string>
using namespace std;
class Account {
double balance = 0;
public:
double getBalance() const {
balance = 1;
return balance;
}
};
int main() {
Account a;
cout << a.getBalance() << endl;
return 0;
}
g++ says:
error: assignment of member 'Account::balance' in read-only object
Rule: every getter (and every function that only reads) should be const.
The setter trap
A common habit is to write a getter and a setter for every private field. Here is a setter that just assigns:
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
Account(string n, double b) : owner(n), balance(b) {}
double getBalance() const { return balance; }
void setBalance(double b) { balance = b; }
void deposit(double amt) { if (amt > 0) balance += amt; }
};
int main() {
Account a("Ravi", 5000);
a.setBalance(-90000);
cout << a.getBalance() << endl;
return 0;
}
Output:
-90000
-90000 again. A setter with no rule inside is just public data with extra typing. Making the data private doesn't protect anything by itself; the public functions you offer decide what is possible.
The fix: expose actions with rules
No setBalance. Instead, offer the actions a real bank offers. withdraw refuses zero, negative amounts and anything more than the balance, and returns true or false so the caller knows what happened.
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
Account(string n, double b) : owner(n), balance(b) {}
double getBalance() const { return balance; }
void deposit(double amt) { if (amt > 0) balance += amt; }
bool withdraw(double amt) {
if (amt <= 0 || amt > balance) return false;
balance -= amt;
return true;
}
};
int main() {
Account a("Ravi", 5000);
if (!a.withdraw(9000)) cout << "Refused: not enough" << endl;
if (a.withdraw(1500)) cout << "Paid 1500" << endl;
cout << a.getBalance() << endl;
return 0;
}
Output:
Refused: not enough
Paid 1500
3500
Whatever main does, the balance can never go negative. A rule that must always be true about an object (here, balance >= 0) is called an invariant, and the class guards it.
Encapsulation
Put together, that is encapsulation:
- Data:
private. - Reading:
constgetters. - Changing: only through actions that check the rules (
deposit,withdraw). - A
setX()that just assigns gives all of that away.
Like a medicine capsule: the medicine is sealed inside, and you only get it the safe way. Encapsulation means keeping the data and the rules that guard it together, inside one class.
class vs struct: the default access
What if you write no label at all?
#include <iostream>
#include <string>
using namespace std;
struct Point {
int x;
};
class Spot {
int x;
};
int main() {
Point p;
p.x = 3;
Spot s;
s.x = 3;
return 0;
}
g++ says:
error: 'int Spot::x' is private within this context
Only s.x fails. In a struct, members are public until you say otherwise; in a class they are private. That (plus the default for inheritance, next episode) is the only real difference between them. By convention, use struct for plain bundles of data (episode 11) and class when there are rules to protect.
protected: family only
Real-life example: a house with three kinds of rooms.
| In a house | In C++ |
|---|---|
| The drawing room: any guest can sit there | public: anyone |
| Your own locker: only you have the key | private: only this class |
| The family kitchen: family yes, guests no | protected: this class and its children |
To see protected, we need a child class (a derived class). class Savings : public Account means "a Savings account is an Account, plus extras". Its constructor passes the balance up to Account's constructor. (Inheritance is the whole topic of episode 15; this is a first look.)
With balance private, even the child is locked out:
#include <iostream>
#include <string>
using namespace std;
class Account {
private:
double balance;
public:
Account(double b) : balance(b) {}
double getBalance() const { return balance; }
};
class Savings : public Account {
public:
Savings(double b) : Account(b) {}
void addInterest() { balance += balance * 0.04; }
};
int main() {
Savings s(10000);
s.addInterest();
cout << s.getBalance() << endl;
return 0;
}
g++ says:
error: 'double Account::balance' is private within this context
error: 'double Account::balance' is private within this context
Change private: to protected::
#include <iostream>
#include <string>
using namespace std;
class Account {
protected:
double balance;
public:
Account(double b) : balance(b) {}
double getBalance() const { return balance; }
};
class Savings : public Account {
public:
Savings(double b) : Account(b) {}
void addInterest() { balance += balance * 0.04; }
};
int main() {
Savings s(10000);
s.addInterest();
cout << s.getBalance() << endl;
return 0;
}
Output:
10400
The child can now use balance (10000 + 4% = 10400). But it is still not public:
#include <iostream>
#include <string>
using namespace std;
class Account {
protected:
double balance;
public:
Account(double b) : balance(b) {}
double getBalance() const { return balance; }
};
class Savings : public Account {
public:
Savings(double b) : Account(b) {}
void addInterest() { balance += balance * 0.04; }
};
int main() {
Savings s(10000);
s.addInterest();
cout << s.getBalance() << endl;
s.balance = 0;
return 0;
}
g++ says:
error: 'double Account::balance' is protected within this context
| Member is... | the class itself | a child class | main / outside |
|---|---|---|---|
private |
yes | no | no |
protected |
yes | yes | no |
public |
yes | yes | yes |
Rule of thumb: start with everything private, and open up only what the outside really needs. Many programmers avoid protected data and give children protected functions instead, so the parent still guards its own invariants.
Why encapsulation pays off: new insides, same buttons
An ATM's buttons stay the same for years, even when the bank replaces everything inside. Because main only uses deposit and getBalance, we can change how the class stores money.
Banks count money in whole paise, because a double can't store values like 0.1 exactly. Here's the double version first:
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
Account(string n, double b) : owner(n), balance(b) {}
double getBalance() const { return balance; }
void deposit(double amt) { if (amt > 0) balance += amt; }
};
int main() {
Account a("Ravi", 5000);
a.deposit(1000.50);
cout << a.getBalance() << endl;
return 0;
}
Output:
6000.5
Now the new insides: a whole number of paise in a long long. The constructor and deposit multiply by 100; the getter divides by 100.0. main is exactly the same:
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
long long paise;
public:
Account(string n, double b) : owner(n), paise(b * 100) {}
double getBalance() const { return paise / 100.0; }
void deposit(double amt) { if (amt > 0) paise += amt * 100; }
};
int main() {
Account a("Ravi", 5000);
a.deposit(1000.50);
cout << a.getBalance() << endl;
return 0;
}
Output:
6000.5
Same output. We rewrote the inside of the class and not one line outside it changed. If main had used balance directly, every such line would now be broken. That is what private buys you: freedom to fix and improve the inside later.
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
| Reading private data from outside | cout << a.balance; |
error: 'double Account::balance' is private within this context |
add a const getter |
| Writing private data from outside | a.balance = -90000; |
error: 'double Account::balance' is private within this context |
go through deposit() / withdraw() |
A non-const getter called on a const object |
double getBalance() used via const Account& |
error: passing 'const Account' as 'this' argument discards qualifiers [-fpermissive] |
double getBalance() const |
A const function that changes a member |
balance = 1; inside getBalance() const |
error: assignment of member 'Account::balance' in read-only object |
don't change members in const functions |
| A child using the parent's private member | balance += ... in Savings |
error: 'double Account::balance' is private within this context |
protected:, or a protected/public function |
Using protected data from main |
s.balance = 0; |
error: 'double Account::balance' is protected within this context |
go through a public function |
Forgetting that class is private by default |
class Spot { int x; }; then s.x = 3; |
error: 'int Spot::x' is private within this context |
add public: where needed |
| A setter with no rule | void setBalance(double b) { balance = b; } |
no message: it compiles, and the balance becomes -90000 |
offer actions with checks instead |
Mini project: a PIN-locked wallet
A wallet locked with a PIN, like a UPI app. Private data: the PIN, the balance and a count of wrong tries. Two const getters (isLocked, getBalance) and one action, pay: refuse if locked; a wrong PIN is counted and refused; the right PIN resets the count; then the usual balance check. main reads PIN and amount pairs until the input ends.
#include <iostream>
#include <string>
using namespace std;
class Wallet {
int pin;
double balance;
int wrong = 0;
public:
Wallet(int p, double b) : pin(p), balance(b) {}
bool isLocked() const { return wrong >= 3; }
double getBalance() const { return balance; }
void pay(int p, double amt) {
if (isLocked()) { cout << "Locked" << endl; return; }
if (p != pin) { wrong++; cout << "Wrong PIN" << endl; return; }
wrong = 0;
if (amt > balance) { cout << "Not enough" << endl; return; }
balance -= amt;
cout << "Paid " << amt << endl;
}
};
int main() {
Wallet w(4321, 2000);
int p; double amt;
while (cin >> p >> amt) w.pay(p, amt);
cout << "Balance: " << w.getBalance() << endl;
return 0;
}
Input:
4321 500
1111 100
2222 100
3333 100
4321 100
Output:
Paid 500
Wrong PIN
Wrong PIN
Wrong PIN
Locked
Balance: 1500
One good payment, three wrong PINs, and then Locked, even with the right PIN. main can't reset the counter or read the PIN, because there is simply no function for it. The only way to change the wallet is the way the class allows.
Extend it: add unlock(int adminCode) (practice 2 below).
Practice
- Give
Studentprivatenameandmarks, a constructor that ignores marks outside 0 to 100,getMarks() const, andaddGrace(int g)that adds grace marks but never goes past 100. - Add
unlock(int adminCode)to the Wallet: the right admin code resets the wrong-PIN count. - Make
Pointa class with privatex,y,constgetters and amove(dx, dy)action. - Find the error message: a function takes
const Account&and calls the non-constdeposit()on it.
Solution
1. The invariant is 0 <= marks <= 100; both the constructor and addGrace guard it.
#include <iostream>
#include <string>
using namespace std;
class Student {
string name;
int marks;
public:
Student(string n, int m) : name(n), marks(0) {
if (m >= 0 && m <= 100) marks = m;
}
int getMarks() const { return marks; }
string getName() const { return name; }
void addGrace(int g) {
if (g <= 0) return;
marks += g;
if (marks > 100) marks = 100;
}
};
int main() {
Student a("Aman", 33);
Student b("Sana", 97);
a.addGrace(5);
b.addGrace(5);
cout << a.getName() << ": " << a.getMarks() << endl;
cout << b.getName() << ": " << b.getMarks() << endl;
return 0;
}
Output:
Aman: 38
Sana: 100
2. The admin code is one more private member; unlock is one more action with a rule.
#include <iostream>
#include <string>
using namespace std;
class Wallet {
int pin;
double balance;
int wrong = 0;
int admin;
public:
Wallet(int p, double b, int a) : pin(p), balance(b), admin(a) {}
bool isLocked() const { return wrong >= 3; }
double getBalance() const { return balance; }
void unlock(int code) {
if (code == admin) { wrong = 0; cout << "Unlocked" << endl; }
else cout << "Wrong admin code" << endl;
}
void pay(int p, double amt) {
if (isLocked()) { cout << "Locked" << endl; return; }
if (p != pin) { wrong++; cout << "Wrong PIN" << endl; return; }
wrong = 0;
if (amt > balance) { cout << "Not enough" << endl; return; }
balance -= amt;
cout << "Paid " << amt << endl;
}
};
int main() {
Wallet w(4321, 2000, 999);
w.pay(1, 100); w.pay(2, 100); w.pay(3, 100);
w.pay(4321, 100);
w.unlock(123);
w.unlock(999);
w.pay(4321, 100);
cout << "Balance: " << w.getBalance() << endl;
return 0;
}
Output:
Wrong PIN
Wrong PIN
Wrong PIN
Locked
Wrong admin code
Unlocked
Paid 100
Balance: 1900
3. Private coordinates, read through const getters, changed only by move.
#include <iostream>
#include <string>
using namespace std;
class Point {
int x, y;
public:
Point(int a, int b) : x(a), y(b) {}
int getX() const { return x; }
int getY() const { return y; }
void move(int dx, int dy) { x += dx; y += dy; }
};
int main() {
Point p(2, 3);
p.move(5, -1);
cout << "(" << p.getX() << ", " << p.getY() << ")" << endl;
return 0;
}
Output:
(7, 2)
4. deposit is not const (it changes the balance), so it can't be called on a const Account&. This is the right answer: a function that promised not to change the account must not deposit into it.
#include <iostream>
#include <string>
using namespace std;
class Account {
double balance;
public:
Account(double b) : balance(b) {}
double getBalance() const { return balance; }
void deposit(double amt) { if (amt > 0) balance += amt; }
};
void addBonus(const Account& acc) {
acc.deposit(100);
}
int main() {
Account a(5000);
addBonus(a);
cout << a.getBalance() << endl;
return 0;
}
g++ says:
error: passing 'const Account' as 'this' argument discards qualifiers [-fpermissive]
Quick quiz
Which line does not compile?
#include <iostream>
#include <string>
using namespace std;
class Box {
int w = 1;
public:
int h = 2;
int getW() const { return w; }
};
int main() {
Box b;
cout << b.h; // A
cout << b.w; // B
cout << b.getW(); // C
b.h = 5; // D
return 0;
}
- A.
cout << b.h; - B.
cout << b.w; - C.
cout << b.getW(); - D.
b.h = 5;
Answer
B (verified). w comes before public:, and in a class that means private, so g++ says error: 'int Box::w' is private within this context. h is public, so A and D are fine, and C reads w through a public const getter.
Interview questions
- What are access specifiers in C++? The labels
private,protectedandpublic, which control which code may use the members that follow them. - What is the difference between
privateandprotected? Private members are usable only by the class's own member functions (and friends); protected members are also usable by classes derived from it. Neither is usable from outside. - What is the default access in a
classand in astruct?privatein a class,publicin a struct. That is the only language difference between them (inheritance also defaults to private forclassand public forstruct). - What is encapsulation? Bundling data with the functions that operate on it, and hiding the data so it can only be changed through those functions, which enforce the object's rules (invariants).
- Is encapsulation the same as data hiding? Data hiding (making members private) is one part. Encapsulation also means the public functions are designed as safe operations, not raw access.
- Why are getters and setters for every field considered a bad smell? A setter that just assigns lets anyone put the object into any state, which is no better than public data. Prefer meaningful actions (
withdraw) that check rules. - What is a
constmember function? One declared withconstafter its parameter list. It promises not to modify the object, and it is the only kind of member function you can call on aconstobject or through aconstreference. - What does "passing 'const X' as 'this' argument discards qualifiers" mean? You called a non-const member function on a const object (or through a const reference/pointer).
- What is an invariant? A condition that must be true for an object whenever it is used from outside, such as
balance >= 0. The class's constructors and public functions keep it true. - Why does encapsulation make code easier to change? Code outside depends only on the public interface, so the private representation (for example
doublerupees tolong longpaise) can change without breaking callers. - Can a member function access private members of another object of the same class? Yes. Access is checked per class, not per object:
Account's functions may read anotherAccount's private members (the copy constructor in episode 13 did this).
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Access specifier | A label that says who may use the members after it | private:, protected:, public: |
private |
Usable only by the class's own member functions | double balance; above public: |
public |
Usable by everyone, including main |
void deposit(double amt) |
protected |
Usable by the class and the classes derived from it, not from outside | protected: double balance; |
| "within this context" | g++'s way of saying "here, at this line" | is private within this context |
| Getter | A public function that returns a private value: a read-only window | double getBalance() const |
| Setter | A public function that sets a private value | void setBalance(double b) |
const member function |
A member function that promises not to change the object | getBalance() const |
this |
Inside a member function, a pointer to the object it was called on | a.getBalance(): this points to a |
| Qualifier | A word like const attached to a type |
const Account& |
| Discards qualifiers | Calling something that would ignore an object's const |
non-const getter on a const Account& |
| Read-only object | An object you may not change (const) | the Account inside a const function |
| Interface | The public functions a class offers to the outside world | deposit, withdraw, getBalance |
| Invariant | A rule that is always true about an object | balance >= 0 |
| Encapsulation | Private data plus the public actions that guard its rules, kept together in one class | the Account and Wallet classes |
| Data hiding | Making members private so outside code can't touch them directly | private: int pin; |
struct |
Like a class, but members are public by default | struct Point { int x; }; |
| Base class (parent) | The class another class is built on | Account |
| Derived class (child) | A class built on another, getting its members plus extras | class Savings : public Account |
| Paise | 1/100 of a rupee; storing whole paise avoids double rounding |
long long paise; |
long long |
A whole-number type with a much bigger range than int |
long long paise; |
Summary
privatemembers can be used only by the class's own functions:maingetsis private within this context.- Making data public lets anyone skip your checks:
a.balance = -90000;compiles silently. - A getter gives read-only access; mark it
const, or it can't be called on aconstobject (discards qualifiers). - A setter that just assigns is public data with extra typing. Offer actions with rules (
deposit,withdraw) that keep the invariant true. - Encapsulation = private data + the public actions that guard it, together in one class.
- A
classis private by default, astructpublic. protectedopens a member to the class and its children, but not tomain(is protected within this context).- Because outside code only uses the public interface, you can change the insides (rupees to paise) without changing
main.
Next episode: inheritance. Today Savings was a child of Account and we only peeked. Next: how to write shared code once in a base class, how a child's constructor talks to its parent's, and the order objects are built and destroyed in.