5.2.5C++ Programming

Classes — member functions, access specifiers (public, private, protected)

1,875 words9 min readdifficulty · medium

1. What is a class? (WHAT)

class BankAccount {
private:                 // walls go up here
    double balance;      // member variable (state)
public:
    void deposit(double amount);   // member function (behaviour)
    double getBalance() const;
};

WHY separate the class from the object? One blueprint (class) can stamp out millions of objects, each with its own copy of the member variables but sharing the same member-function code.


2. Access specifiers — the three walls (WHAT + WHY)

Specifier Same class Derived class Outside (main)
public
protected
private
Figure — Classes — member functions, access specifiers (public, private, protected)

3. Member functions (HOW)

Defining inside vs outside the class

class BankAccount {
private:
    double balance = 0;
public:
    // (a) defined INSIDE → implicitly inline
    double getBalance() const { return balance; }
 
    // (b) declared inside, DEFINED OUTSIDE with scope resolution ::
    void deposit(double amount);
};
 
void BankAccount::deposit(double amount) {   // :: ties it to the class
    balance += amount;        // 'balance' really means this->balance
}

4. Full worked example (Derivation-from-scratch)

#include <iostream>
using namespace std;
 
class Rectangle {
private:                              // STEP 1: hide raw data
    double width, height;
public:
    // STEP 2: controlled way to set state (validates input!)
    void setDimensions(double w, double h) {
        if (w < 0 || h < 0) { width = height = 0; return; }
        width = w; height = h;
    }
    // STEP 3: read-only computed property
    double area() const { return width * height; }
};
 
int main() {
    Rectangle r;
    r.setDimensions(3, 4);            // ✅ public gateway
    cout << r.area();                 // prints 12
    // r.width = -5;                  // ❌ blocked: cannot create invalid state
}

Why STEP 1? If width/height were public, anyone could set a negative width → an impossible rectangle. Why STEP 2 validates? The only door into the data also acts as a guard — invalid states become unrepresentable. Why area() is const? Computing area doesn't change the rectangle; marking it const documents and enforces that.


5. Common mistakes (Steel-man + fix)


6. The 80/20 core


Recall Feynman: explain to a 12-year-old

Imagine a vending machine. Inside it there's money and snacks (the private data) — you can't reach in and grab them. On the outside there are buttons (the public functions): "insert coin", "press B4". You only interact through the buttons, and the machine makes sure you can't steal or break things. A class is the design of one vending machine; each actual machine in the hallway is an object. Private = stuff locked inside the box. Public = the buttons. Protected = a secret repair panel only the machine's family of repair-machines can open, but not customers.


Connections


Flashcards

What are the three access specifiers in C++?
public, private, protected
What is the default access level in a class?
private
What is the default access level in a struct?
public
Where can a private member be accessed?
Only inside the class's own member functions (and friends)
What does protected add over private?
Access from derived (child) classes too
Access in C++ is per-class or per-object?
Per-class — one object's method can read another same-class object's private members
What does the hidden this pointer point to?
The object the member function was called on
What does const after a member function signature guarantee?
The function will not modify the object's members
What operator ties an externally-defined function to its class?
Scope resolution operator ::
Why hide data behind public functions?
To enforce invariants/validation and make invalid states unrepresentable (encapsulation)
Can you call a non-const member function on a const object?
No — only const member functions

Concept Map

instantiates

bundles

bundles

plus behaviour equals

plus data equals

enforced by

open to all

class only

class plus children

default for

carries hidden

points to

safe API like deposit

Class blueprint

Object instance

Member variables

Member functions

Encapsulation

Access specifiers

public

private

protected

this pointer

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, ek class ka matlab hai ek blueprint — jaise vending machine ka design. Usme do cheezein hoti hain: data (member variables, jaise balance) aur functions (member functions, jaise deposit()). In dono ko ek saath bundle karna hi encapsulation kehlata hai. Asli faayda ye hai ki hum data ko bahar wale logon se chhupa sakte hain, taaki koi galat tareeke se balance = -9999 na kar de.

Ab access specifiers wo deewaarein hain jo decide karti hain kaun kya chhoo sakta hai. private matlab sirf apni class ke andar — bilkul locked. public matlab sabke liye open, jaise vending machine ke buttons. Aur protected ek beech ka level hai: apni class plus bachche (derived classes) use kar sakte hain, lekin bahar wala main() nahi. Yaad rakho — class me by default sab kuch private hota hai, jabki struct me public. Bas yahi ek difference hai dono me.

Member functions ke paas ek chhupa hua this pointer hota hai jo bata raha hai "main kis object pe kaam kar raha hoon." Agar function object ko change nahi karta, to uske aage const likho — ye ek promise hai compiler ko, aur compiler isse enforce bhi karta hai. Class ke bahar function define karne ke liye ReturnType ClassName::function() likhte hain, jisme :: batata hai ki ye function kis class ka hai.

80/20 baat ye hai: data ko private rakho, usse access karne ke liye public functions (gateways) banao jo validation bhi karein. Isse "invalid state" possible hi nahi rahega — yahi professional C++ code ka core hai. Exam aur interview dono me ye table (kaun-kaun access kar sakta hai) zaroor poocha jaata hai, to ratta nahi, samajh ke yaad karo.

Go deeper — visual, from zero

Test yourself — C++ Programming

Connections