These are the notes for C++ episode 12. Episode 11 ended with a struct happily accepting 250 marks out of 100. Here a bank account shows why that is dangerous (a balance of minus 2000), and you will invent the fix one step at a time: member functions that keep the rules inside the type, private data and public functions, the class, and the difference between a class and an object. Then you'll define member functions outside the class with ::, write a getter, and build a cricket batter class that refuses impossible scores. 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.
The problem: a balance of minus 2000
A bank account as a struct from last episode. Ravi has 5000 rupees and asks the ATM for 7000. The ATM code just subtracts:
#include <iostream>
#include <string>
using namespace std;
struct Account {
string owner;
double balance;
};
int main() {
Account a = {"Ravi", 5000};
// ATM: withdraw 7000
a.balance = a.balance - 7000;
cout << a.owner << ": " << a.balance << endl;
return 0;
}
Output:
Ravi: -2000
The bank just handed out 2000 rupees that Ravi never had.
Why it failed: the rule "never give out more than the balance" isn't anywhere near the data. Every piece of code that touches balance (the ATM, the mobile app, the branch counter...) has to remember the rule. If it's written in fifty places, one of them will forget.
Step 1: put the rule inside the type (member functions)
Write the rule once, inside Account, and let everyone ask the account instead of subtracting by hand. A function that lives inside a struct or class is a member function (also called a method).
#include <iostream>
#include <string>
using namespace std;
struct Account {
string owner;
double balance;
void withdraw(double amt) {
if (amt > balance) cout << "Not enough money" << endl;
else balance = balance - amt;
}
};
int main() {
Account a = {"Ravi", 5000};
a.withdraw(7000);
a.withdraw(1500);
cout << a.owner << ": " << a.balance << endl;
return 0;
}
Output:
Not enough money
Ravi: 3500
- You call a member function on an object, with the dot:
a.withdraw(7000). - Inside it, members are used directly: just
balance, nota.balance. A member function always works on the object it was called on, so ina.withdraw(...),balancemeans a's balance.
But the rule can still be skipped
#include <iostream>
#include <string>
using namespace std;
struct Account {
string owner;
double balance;
void withdraw(double amt) {
if (amt > balance) cout << "Not enough money" << endl;
else balance = balance - amt;
}
};
int main() {
Account a = {"Ravi", 5000};
a.withdraw(7000);
a.balance = a.balance - 7000;
cout << a.owner << ": " << a.balance << endl;
return 0;
}
Output:
Not enough money
Ravi: -2000
The rule exists, but a careless line walks around it, because balance is still open to the whole program.
Step 2: lock the data (private and public)
How does a real ATM stop this? You can't open the cash vault; you can only press the buttons, and every button runs the bank's checks first.
| At the ATM | In C++ | Meaning |
|---|---|---|
| The cash vault, locked inside | private: data |
only the type's own functions can touch it |
| The keypad buttons | public: functions |
the actions the outside world may use |
| The machine checks first | the rule inside withdraw |
there is no way around it |
private and public are access specifiers: labels that say who may use the members after them.
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
void open(string n, double b) { owner = n; balance = b; }
void withdraw(double amt) {
if (amt > balance) cout << "Not enough money" << endl;
else balance = balance - amt;
}
void show() { cout << owner << ": " << balance << endl; }
};
int main() {
Account a;
a.open("Ravi", 5000);
a.withdraw(7000);
a.show();
return 0;
}
Output:
Not enough money
Ravi: 5000
- We changed the word
structtoclass. In a class, everything is private unless you say otherwise, soownerandbalanceare locked away. public:(with a colon) makes everything after it usable from outside:open,withdraw,show.- Braces like
Account a = {"Ravi", 5000};can no longer fill private data (see the mistakes table), so for nowopenfills it in. Episode 13 replacesopenwith something better: a constructor.
Now the careless line again, a.balance = a.balance - 7000; in main:
main.cpp:20:7: error: 'double Account::balance' is private within this context
The compiler refuses. The mistake is caught before the program even builds, not at the bank, not at run time.
class vs struct
| default access | typical use | |
|---|---|---|
struct Account { ... }; |
public | a plain bundle of data (a date, a point) |
class Account { ... }; |
private | data plus rules to protect (an account, a batter) |
In C++ that default is the only difference: a struct can have member functions and private members, and a class can have public data. Both end with };.
Class vs object: one flat plan, many flats
A builder draws one 2BHK flat plan. Nobody lives in a plan; it's paper. From it, the builder builds flat 101 and flat 204. Each flat has its own furniture: paint 101 and 204 doesn't change.
| In a housing society | In C++ |
|---|---|
| The flat plan | the class Account: describes what every account has and can do |
| Flat 101, flat 204 | objects a and b: real things built from the class |
| Each flat's own furniture | each object's own copy of the data; the functions are shared |
Creating an object from a class is called instantiation; an object is an instance of its class.
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
void open(string n, double b) { owner = n; balance = b; }
void withdraw(double amt) {
if (amt > balance) cout << "Not enough money" << endl;
else balance = balance - amt;
}
void show() { cout << owner << ": " << balance << endl; }
};
int main() {
Account a, b;
a.open("Ravi", 5000); b.open("Priya", 800);
a.withdraw(1500); b.withdraw(1500);
a.show(); b.show();
return 0;
}
Output:
Not enough money
Ravi: 3500
Priya: 800
Same withdraw code, different results: a.withdraw used a's balance (5000, so it went through), b.withdraw used b's (800, so "Not enough money").
Defining member functions outside the class
Real classes have many functions. To keep the class readable, programmers often put only the declarations inside (the function's first line, ending with ;) and write the bodies outside. The obvious attempt:
#include <iostream>
#include <string>
using namespace std;
class Account {
double balance = 0;
public:
void deposit(double amt);
double getBalance() { return balance; }
};
void deposit(double amt) {
balance = balance + amt;
}
int main() {
Account a;
a.deposit(500);
a.deposit(250);
cout << "Balance: " << a.getBalance() << endl;
return 0;
}
g++ says:
main.cpp:13:5: error: 'balance' was not declared in this scope
Why: outside the class, void deposit(...) is just an ordinary function that happens to be called deposit. Nothing says it belongs to Account, so it has no balance.
The fix: void Account::deposit(double amt). The :: is the scope resolution operator, the same one as in std::cout. Account::deposit means "the deposit that belongs to Account".
#include <iostream>
#include <string>
using namespace std;
class Account {
double balance = 0;
public:
void deposit(double amt);
double getBalance() { return balance; }
};
void Account::deposit(double amt) {
balance = balance + amt;
}
int main() {
Account a;
a.deposit(500);
a.deposit(250);
cout << "Balance: " << a.getBalance() << endl;
return 0;
}
Output:
Balance: 750
getBalance() is a getter: a public function that returns a private value. Outside code can read the balance but has no way to set it directly. (double balance = 0; is a default member value from episode 11.) Episode 14 goes deeper into getters, setters and encapsulation.
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says | Fix |
|---|---|---|---|
| Touching private data from outside | a.balance = a.balance - 7000; |
error: 'double Account::balance' is private within this context |
call a public function: a.withdraw(7000); |
| Calling a private function | a.deposit(500); where deposit is above public: |
error: 'void Account::deposit(double)' is private within this context |
put it after public: |
| Braces on a class with private data | Account a = {"Ravi", 5000}; |
error: could not convert '{"Ravi", 5000}' from '<brace-enclosed initializer list>' to 'Account' |
a.open(...) for now; constructors in episode 13 |
| Body outside without the class name | void deposit(double amt) { balance = ... } |
error: 'balance' was not declared in this scope |
void Account::deposit(double amt) |
| Calling a member function without an object | deposit(500); in main |
error: 'deposit' was not declared in this scope |
a.deposit(500); |
| Calling a function the class doesn't have | a.show; |
error: 'class Account' has no member named 'show' |
add the member, or fix the name |
| No semicolon after the class | class Account { ... } |
error: expected ';' after class definition |
class Account { ... }; |
Mini project: a cricket scorer
A struct could never stop someone typing 9 runs off one ball. A class can. face accepts 0 to 6 runs and ignores anything else.
#include <iostream>
#include <string>
using namespace std;
class Batter {
string name; int runs = 0, balls = 0;
public:
void setName(string n) { name = n; }
void face(int r) {
if (r < 0 || r > 6) return;
runs = runs + r; balls = balls + 1;
}
void show() {
cout << name << ": " << runs << " off " << balls << endl;
}
};
int main() {
Batter a;
a.setName("Ravi");
int shots[7] = {4, 0, 6, 9, 1, 1, 4};
for (int i = 0; i < 7; i++) a.face(shots[i]);
a.show();
return 0;
}
Output:
Ravi: 16 off 6
Seven shots, but only 6 balls counted: the impossible 9 was refused, so it can't spoil the scorecard. return; in a void function simply leaves it early.
Extend it: count fours and sixes, and add a strike-rate function (runs * 100.0 / balls).
The next problem: an object nobody set up
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
public:
void open(string n, double b) { owner = n; balance = b; }
void withdraw(double amt) {
if (amt > balance) cout << "Not enough money" << endl;
else balance = balance - amt;
}
void show() { cout << owner << ": " << balance << endl; }
};
int main() {
Account c;
c.show();
return 0;
}
One run printed:
: 6.95262e-310
An empty name and a garbage balance (the number changes from run to run). We forgot to call open. The class protects its data from bad changes, but nothing forces it to start correct. Episode 13 invents the fix: constructors.
Practice
- Add
deposit()toAccountthat refuses 0 or negative amounts. - Write
class Studentwith privatemarks;setMarks()accepts only 0 to 100, andgetMarks()returns it. - Make 3
Studentobjects and print the topper. - Move every function body of
Studentoutside the class withStudent::.
Solution
1. One if guards the private balance.
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance = 0;
public:
void open(string n, double b) { owner = n; balance = b; }
void deposit(double amt) {
if (amt <= 0) cout << "Invalid amount" << endl;
else balance = balance + amt;
}
void show() { cout << owner << ": " << balance << endl; }
};
int main() {
Account a;
a.open("Ravi", 5000);
a.deposit(-300);
a.deposit(700);
a.show();
return 0;
}
Output:
Invalid amount
Ravi: 5700
2 and 3. setMarks is the only way in, so marks can never be 250. Objects start with marks = 0.
#include <iostream>
#include <string>
using namespace std;
class Student {
string name;
int marks = 0;
public:
void setName(string n) { name = n; }
void setMarks(int m) {
if (m < 0 || m > 100) cout << "Rejected " << m << " for " << name << endl;
else marks = m;
}
int getMarks() { return marks; }
string getName() { return name; }
};
int main() {
Student s[3];
s[0].setName("Ravi"); s[0].setMarks(65);
s[1].setName("Priya"); s[1].setMarks(250);
s[2].setName("Sana"); s[2].setMarks(88);
int top = 0;
for (int i = 1; i < 3; i++) {
if (s[i].getMarks() > s[top].getMarks()) top = i;
}
cout << "Topper: " << s[top].getName() << " " << s[top].getMarks() << endl;
return 0;
}
Output:
Rejected 250 for Priya
Topper: Sana 88
An array of objects works just like an array of structs: s[1].setMarks(250).
4. Declarations inside, bodies outside with Student::.
#include <iostream>
#include <string>
using namespace std;
class Student {
string name;
int marks = 0;
public:
void setName(string n);
void setMarks(int m);
int getMarks();
};
void Student::setName(string n) {
name = n;
}
void Student::setMarks(int m) {
if (m >= 0 && m <= 100) marks = m;
}
int Student::getMarks() {
return marks;
}
int main() {
Student s;
s.setName("Ravi");
s.setMarks(250);
s.setMarks(91);
cout << s.getMarks() << endl;
return 0;
}
Output:
91
Quick quiz
What does this print?
#include <iostream>
#include <string>
using namespace std;
class Box {
int v = 1;
public:
void add(int n) { v = v + n; }
int get() { return v; }
};
int main() {
Box p, q;
p.add(5);
q.add(p.get());
cout << q.get() << endl;
return 0;
}
- A.
1 - B.
6 - C.
7 - D. Compile error
Answer
C: 7 (verified). p and q are separate objects, each with its own v starting at 1. p.add(5) makes p's v 6. q.add(p.get()) adds 6 to q's own 1, so q.get() is 7.
Interview questions
- What is a class? What is an object? A class is a user-defined type, a blueprint that describes data (members) and behaviour (member functions). An object is an instance of a class: a real thing in memory with its own copy of the data.
- What is the difference between a class and a struct in C++? Only the default access: class members are private by default, struct members are public by default. Everything else is the same.
- What are access specifiers?
public,privateandprotected. They control who may use a member: anyone (public), only the class's own member functions (and friends) (private), or also derived classes (protected, episode 15). - Why make data members private? So every change goes through member functions that enforce the rules (no negative balance, marks 0 to 100). This is encapsulation, and it means a rule lives in one place.
- What is a member function, and how does it know which object to work on? A function declared inside a class. It's called on an object (
a.withdraw(...)), and inside it, members refer to that object's data. (Under the hood C++ passes a hidden pointer calledthis, episode 18.) - What does
::mean invoid Account::deposit(double amt)? It's the scope resolution operator: thisdepositis the member ofAccount, defined outside the class body. - What is a getter? A public member function that returns the value of a private member, so outside code can read it without being able to change it directly.
- Is "is private within this context" a run-time or compile-time error? Compile-time. Access rules are checked by the compiler; a program that breaks them is never built.
- Do objects of the same class share data? No. Each object has its own data members; the member functions' code is shared.
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Class | A blueprint: a type that bundles data and the functions that work on it | class Account { ... }; |
| Object | A real thing built from a class, with its own data | Account a; |
| Instance | Another word for an object of a class | a is an instance of Account |
| Instantiation | Creating an object from a class | Account a, b; |
| Member function (method) | A function declared inside a class or struct | void withdraw(double amt) |
| Data member | A variable declared inside a class or struct | double balance; |
| Access specifier | A label saying who may use the members after it | public:, private: |
private |
Usable only by the class's own member functions | balance in class Account |
public |
Usable by any code | withdraw, show |
| Default access | The access members get when no label is written: private in a class, public in a struct | class Account { double balance; ... } |
| Encapsulation | Keeping data private and allowing changes only through functions that check the rules | withdraw refuses 7000 |
| Declaration (of a function) | Its first line, ending with ;, without a body |
void deposit(double amt); |
| Definition (of a function) | The function with its body | void Account::deposit(double amt) { ... } |
Scope resolution operator (::) |
Says which class or namespace a name belongs to | Account::deposit, std::cout |
| Scope | The region of code where a name is known | balance is in Account's scope |
| Getter | A public function that returns a private value | double getBalance() |
| Setter | A public function that changes a private value, after checking it | void setMarks(int m) |
| Interface | The public functions of a class: what others can do with it | open, withdraw, show |
| Compile-time error | A mistake the compiler finds; no program is produced | is private within this context |
| Garbage value | Leftover bits in memory read as a value; changes from run to run | 6.95262e-310 |
| Object-oriented programming (OOP) | Building programs from objects that combine data and behaviour | classes and objects |
Summary
- A struct with open data let an ATM leave Ravi at minus 2000: the rule lived nowhere near the data.
- Member functions put the rule inside the type:
a.withdraw(7000)refuses. Inside, members are used directly (balance). - But open data can still be changed by hand.
privatelocks the data;publicfunctions are the only way in. Breaking this is a compile error:is private within this context. classis private by default,structis public by default; that is the only difference.- A class is the plan; an object is a real thing built from it, with its own data.
- Define a member outside the class with
Account::name; without it:'balance' was not declared in this scope. - A getter lets others read private data without changing it.
- An object that is never set up holds garbage. Next: constructors.
Next episode: constructors and destructors. Today an account we forgot to open printed garbage. Next time, an object can't even exist without a name and a balance, and cleans up after itself when it dies.