Class Basics

Back

Loading concept...

🏠 C++ Classes: Building Your First Digital House

The Big Picture

Imagine you’re building a house. Before you start hammering nails, you need a blueprint. This blueprint tells everyone:

  • What rooms the house will have (bedrooms, kitchen, bathroom)
  • Which rooms guests can enter (living room) and which are private (your bedroom)
  • What’s inside each room (furniture, decorations)

In C++, a class is exactly like that blueprint! It’s a plan for creating things in your program.


🎯 What You’ll Learn

  1. Class Definition — How to draw your blueprint
  2. Access Specifiers — Which doors are locked or open
  3. Class Members — The rooms and furniture inside
  4. this Pointer — How the house knows “I am THIS house”

1. Class Definition: Drawing the Blueprint

What is a Class?

A class is a recipe or template for creating objects. Just like a cookie cutter makes cookies, a class makes objects!

Think of it this way:

  • 🍪 Cookie cutter = Class (the template)
  • 🍪 Actual cookie = Object (the real thing you made)

How to Write a Class

class Dog {
    // Everything about
    // dogs goes here!
};  // Don't forget this!

Super Important: Always end with }; — the semicolon is like saying “The End” after a story!

A Complete Example

class Dog {
public:
    string name;
    int age;

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

Now you can create actual dogs:

Dog myPet;        // Made a dog!
myPet.name = "Buddy";
myPet.age = 3;
myPet.bark();     // Prints: Woof!

🧠 Remember This

Blueprint (Class) Real Thing (Object)
class Dog Dog myPet
Describes a dog IS a specific dog
No memory used Uses memory

2. Access Specifiers: Open Doors vs Locked Doors

The Three Types of Doors

Imagine your house has three types of doors:

Specifier Door Type Who Can Enter?
public 🚪 Open door Everyone can come in
private 🔒 Locked door Only family (the class itself)
protected 🔑 Special key Family and close relatives (children classes)

Why Lock Some Doors?

Would you want strangers walking into your bedroom and moving your stuff around? No way!

Same with code — you want to protect important data from being changed by accident.

Example: A Piggy Bank

class PiggyBank {
private:
    int money;  // Hidden inside!

public:
    void addMoney(int coins) {
        if (coins > 0) {
            money = money + coins;
        }
    }

    int checkBalance() {
        return money;
    }
};

Why is money private?

  • Nobody can directly steal coins!
  • We control HOW money goes in (must be positive)
  • We can always check balance safely
PiggyBank myBank;
// myBank.money = -100; ← ERROR!
// Can't touch private stuff!

myBank.addMoney(50);    // ✓ Works!
cout << myBank.checkBalance();

Default is Private!

class Secret {
    int hidden;  // This is PRIVATE
                 // by default!
};

If you don’t say public: or private:, C++ assumes private. It’s like the door locks automatically!


3. Class Members: What’s Inside Your House

Two Types of Members

A class has two kinds of things inside:

  1. Data Members (Variables) — The furniture, the stuff
  2. Member Functions (Methods) — The actions, what you can do

Think of a TV remote:

  • Data: Current channel, volume level, on/off state
  • Functions: Change channel, adjust volume, power button

Example: TV Remote Class

class Remote {
private:
    int channel;
    int volume;
    bool isOn;

public:
    void powerOn() {
        isOn = true;
    }

    void changeChannel(int ch) {
        if (ch > 0 && ch < 1000) {
            channel = ch;
        }
    }

    void volumeUp() {
        if (volume < 100) {
            volume = volume + 1;
        }
    }
};

Visual Map

graph TD A["class Remote"] --> B["Private Members"] A --> C["Public Members"] B --> D["int channel"] B --> E["int volume"] B --> F["bool isOn"] C --> G["powerOn"] C --> H["changeChannel"] C --> I["volumeUp"]

Accessing Members

Use the dot operator . to access members:

Remote myRemote;
myRemote.powerOn();
myRemote.changeChannel(5);
myRemote.volumeUp();

It’s like saying: “Hey myRemote, do powerOn()!”


4. The this Pointer: “I Am THIS Object!”

The Problem

Imagine you’re in a room with 100 identical twin robots. Each robot needs to know “Which one am I?”

That’s what this does — it tells an object “YOU are the one being talked to!”

What is this?

  • this is a pointer that points to the current object
  • Every object has its own this
  • It’s like a nametag that says “THIS IS ME!”

When Do You Need this?

Problem: When a parameter has the same name as a member:

class Cat {
private:
    string name;

public:
    void setName(string name) {
        // Uh oh! Both are
        // called "name"!
        // Which is which?

        this->name = name;
        //   ↑          ↑
        // member   parameter
    }
};
  • this->name = “MY name” (the cat’s name)
  • name = “the name given to me” (the parameter)

Real-World Analogy

Imagine you’re filling out a form:

“Please write your name: _____”

You write YOUR name, not someone else’s. this is how the object knows it’s filling in ITS OWN information!

Complete Example

class Student {
private:
    string name;
    int grade;

public:
    void setInfo(string name,
                 int grade) {
        this->name = name;
        this->grade = grade;
    }

    void introduce() {
        cout << "Hi, I am ";
        cout << this->name;
    }
};
Student alice;
Student bob;

alice.setInfo("Alice", 5);
bob.setInfo("Bob", 6);

alice.introduce();
// Prints: Hi, I am Alice
// (alice knows SHE is alice)

bob.introduce();
// Prints: Hi, I am Bob
// (bob knows HE is bob)

The Magic Behind the Scenes

When you call alice.introduce(), C++ secretly does this:

introduce(&alice)  // Passes alice's
                   // address as 'this'

So inside the function, this points to alice!


🎯 Quick Summary

graph TD A["C++ Class"] --> B["Definition"] A --> C["Access Specifiers"] A --> D["Members"] A --> E["this Pointer"] B --> B1["class Name &#123; &#125;;"] C --> C1["public: Everyone"] C --> C2["private: Only class"] C --> C3["protected: Family"] D --> D1["Data: Variables"] D --> D2["Functions: Actions"] E --> E1["Points to current object"] E --> E2["this-&gt;member"]

🌟 You Did It!

You now understand the foundations of C++ classes:

Class Definition — Your blueprint for creating objects ✅ Access Specifiers — Control who can touch what ✅ Class Members — The data and actions inside ✅ this Pointer — How objects know themselves

Think of a class like a superhero’s identity card:

  • Name: Superman (class name)
  • Secret Identity: Clark Kent (private data)
  • Public Powers: Flying, strength (public functions)
  • “I am Superman”: The this pointer!

Now go create your own digital blueprints! 🚀

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.