Class Members

Back

Loading concept...

C++ Class Members: The Secret Powers Inside Your Classes

Imagine your class is a clubhouse. Regular members come and go, each with their own locker. But some things belong to the whole club—like a shared scoreboard. And some members have special powers—like being ā€œread-onlyā€ or having a ā€œbackstage pass.ā€ Let’s discover these special powers!


šŸ† Static Members: The Shared Scoreboard

What Are They?

Static members belong to the entire class, not to any single object. Think of it like the clubhouse scoreboard—everyone sees the same score, no matter who you are.

class Player {
public:
    static int totalPlayers;
    string name;

    Player(string n) : name(n) {
        totalPlayers++;
    }
};

int Player::totalPlayers = 0;

What happens:

  • Create Player ā€œAliceā€ → totalPlayers = 1
  • Create Player ā€œBobā€ → totalPlayers = 2
  • Both Alice and Bob see the same count!

Static Variables vs Regular Variables

Regular Member Static Member
Each object has its own copy One copy for ALL objects
Created with each object Created once, lives forever
Accessed via object Accessed via class name

Static Functions: The Class Helper

Static functions can ONLY touch static members. They don’t know about individual objects!

class Counter {
    static int count;
public:
    static void showCount() {
        cout << count;
    }
};

Simple Rule: Static = Shared by everyone. Like a TV in the clubhouse—one TV, everyone watches.


šŸ”’ Const Member Functions: The Promise Keepers

What Are They?

A const member function makes a promise: ā€œI will NOT change anything!ā€

class BankAccount {
    int balance;
public:
    int getBalance() const {
        return balance;
    }
};

That little const at the end means: ā€œThis function only LOOKS, never TOUCHES.ā€

Why Use Them?

graph TD A["const Function"] --> B["Can READ data"] A --> C["Cannot CHANGE data"] A --> D["Safe to call anytime"] B --> E["Perfect for getters!"]

The Golden Rules

  1. Const functions can’t modify members
  2. Const functions can only call other const functions
  3. Const objects can ONLY call const functions
class Dog {
    string name;
public:
    string getName() const {
        return name;
    }

    void bark() {
        cout << "Woof!";
    }
};

const Dog buddy("Buddy");
buddy.getName();  // OK!
buddy.bark();     // ERROR! bark() isn't const

šŸŽ­ Mutable Keyword: The Exception Maker

The Problem

What if you have a const function, but you NEED to change ONE tiny thing? Like counting how many times someone looked at something?

The Solution: Mutable!

class Document {
    string content;
    mutable int viewCount;
public:
    string read() const {
        viewCount++;  // Allowed because mutable!
        return content;
    }
};

Mutable means: ā€œEven in a const function, this variable CAN change.ā€

When to Use It

graph TD A["Use mutable for:"] --> B["Counters/Stats"] A --> C["Caching"] A --> D["Logging"] B --> E["viewCount++"] C --> F["Save expensive calculations"] D --> G["Track access times"]

Real Example: A library book’s content never changes, but we track how many times it’s borrowed!

class LibraryBook {
    const string text;
    mutable int borrowCount;
public:
    string getText() const {
        borrowCount++;
        return text;
    }
};

šŸŽ« Friend Functions: The VIP Pass

The Concept

Normally, private members are… private! But sometimes you need to give someone a backstage pass.

class SecretBox {
    int secret = 42;
    friend void peekInside(SecretBox& box);
};

void peekInside(SecretBox& box) {
    cout << box.secret;  // Can see private!
}

The friend keyword says: ā€œThis function gets VIP access!ā€

Why Use Friends?

Regular Function Friend Function
Can only see public Can see EVERYTHING
Uses interface Direct access
Respects privacy Has the password

Friend Function Example

class Rectangle {
    int width, height;
public:
    Rectangle(int w, int h)
        : width(w), height(h) {}

    friend int calculateArea(Rectangle& r);
};

int calculateArea(Rectangle& r) {
    return r.width * r.height;
}

šŸ  Friend Classes: The Whole Family Gets In

What If Another Class Needs Access?

class Wallet {
    int money = 100;
    friend class Spouse;
};

class Spouse {
public:
    void checkWallet(Wallet& w) {
        cout << w.money;  // Can see private!
    }
};

When a class is a friend, ALL its functions get VIP access!

One-Way Friendship

Important: Friendship is NOT mutual!

graph LR A["Class A"] -->|friend| B["Class B"] B -.->|NO access| A style A fill:#90EE90 style B fill:#FFB6C1

Just because A trusts B doesn’t mean B trusts A!

class Kitchen {
    friend class Chef;  // Chef can access Kitchen
};

class Chef {
    int secretRecipe;   // Kitchen can NOT see this!
};

šŸŽÆ Quick Summary

Feature What It Does Analogy
Static Shared by all objects Club scoreboard
Const Promise not to change Museum guide
Mutable Exception to const Emergency key
Friend VIP access granted Backstage pass

šŸ’” Remember This!

Static = One for ALL (like the sun—everyone shares it)

Const = ā€œI only look, never touchā€ (like a security camera)

Mutable = ā€œBut THIS one thing I can changeā€ (like a visitor counter)

Friend = ā€œYou’re allowed in my houseā€ (but only if I say so!)


šŸš€ Pro Tips

  1. Use static for counters, shared configs, or utility functions
  2. Mark getters as const — it’s good practice!
  3. Use mutable sparingly — for caching and counting only
  4. Friends break encapsulation — use only when necessary

Now you know the secret powers of C++ class members! Each one solves a specific problem, and together they make your classes powerful and flexible.

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.