01 / 21

Defining Classes with
Access Specifiers

Learn how to build classes in C++ using private and public sections to control access, protect data, and write robust object-oriented code.

C++

What Is a Class?

A class is a user-defined blueprint that bundles related data (member variables) and behavior (member functions) into a single, reusable unit. Think of it as a custom type you design yourself.

BankAccount private: balance ownerName public: deposit() getBalance() Hidden data Public interface

Class vs. Object

A class is the blueprint; an object is a concrete instance of that blueprint. You can create many objects from one class, each holding its own copy of the data.

Class
The template: defines member variables and member functions. No memory is allocated until you create an object.
Object
A specific instance: occupies memory, holds actual values, and can call the class's member functions.

Why Access Control Matters

Without access specifiers, any code anywhere could modify an object's internal data: leading to bugs, invalid states, and code that is painful to maintain.

No Protection balance = -9999 name = "" Any code can set invalid values directly ✕ With Access Control deposit() validates setName() checks input Only controlled methods can modify internal data ✓

The Three Access Specifiers

private
Accessible only inside the class itself. Default for class members. Use for internal data.
public
Accessible from anywhere: inside the class, from objects, from other functions. Use for the interface.
protected
Like private, but also accessible to derived classes (subclasses). Used in inheritance hierarchies.

Syntax Blueprint

class ClassName {
private:
    // Hidden data members
    int secretValue;

public:
    // Accessible interface
    void setValue(int v);
    int getValue() const;
}; // <-- semicolon required!

private vs. public: The Wall

Rectangle class private: double width; double height; public: setDimensions(w, h) getArea() getPerimeter() main() ✕ ✓

class vs. struct

class struct
Default access private public
Typical use Complex objects with encapsulation Simple data bundles (POD types)
Can have methods? Yes Yes
Convention OOP design, hidden state Lightweight, all-public data

How to Define a Class

1
Choose a name that describes the object (e.g., Student, Circle).
2
List private data: what the object needs to remember internally.
3
Design public functions: how outside code will interact with the object.
4
Write the class body using private: and public: labels.
5
End with a semicolon after the closing brace }.

Example 1: Circle Class

class Circle {
private:
    double radius;

public:
    void setRadius(double r) {
        if (r > 0) radius = r;
    }

    double getArea() const {
        return 3.14159 * radius * radius;
    }
};

Using the Circle Object

// Requires #include <iostream>
int main() {
    Circle c;
    c.setRadius(5.0); // ✓ public function

    std::cout << c.getArea(); // ✓ prints ~78.54

    // c.radius = -3; ✕ ERROR: private!
    return 0;
}

Example 2: Student Class

// Requires #include <string>
class Student {
private:
    std::string name;
    int grade; // 0-100

public:
    void setName(std::string n) { name = n; }

    void setGrade(int g) {
        if (g >= 0 && g <= 100)
            grade = g;
    }

    std::string getName() const { return name; }
    int getGrade() const { return grade; }
};

Getters and Setters

Since private members cannot be read or modified from outside the class, we provide getter functions (read) and setter functions (write) as the controlled public interface.

Getter
Returns the value of a private member. Usually marked const because it does not modify the object.
Setter
Accepts a parameter and assigns it to a private member, typically with validation logic to reject bad input.

Example 3: BankAccount

class BankAccount {
private:
    double balance;

public:
    BankAccount() { balance = 0.0; }

    void deposit(double amt) {
        if (amt > 0) balance += amt;
    }

    bool withdraw(double amt) {
        if (amt > 0 && amt <= balance) {
            balance -= amt;
            return true;
        }
        return false;
    }

    double getBalance() const {
        return balance;
    }
};

Common Mistakes

✕ Missing Semicolon
Forgetting the ; after the closing brace of the class. This causes cryptic compiler errors on the next line.
✕ Everything Public
Declaring all members public defeats the purpose of encapsulation. Data members should almost always be private.
✕ No Validation
Writing setters that blindly assign without checking. A setter without validation is no safer than a public variable.

Summary Cheat Sheet

Concept Key Point Example
class keyword Declares a new type class Circle { };
private Default; hidden data double radius;
public Visible interface void setRadius(double);
Getter Reads private data double getArea() const;
Setter Writes with validation void setRadius(double r);
Semicolon Required after }; }; // don't forget!

Question 1 of 5

What is the default access level for members of a C++ class?

Question 2 of 5

Given the class below, which line in main() would cause a compiler error?

class Dog {
private:
    int age;
public:
    void setAge(int a) { age = a; }
    int getAge() { return age; }
};

Question 3 of 5

Why do we mark a getter function with the const keyword?

Question 4 of 5

What happens if you forget the semicolon after the closing brace of a class definition?

Question 5 of 5

A setter function that does not validate its input is equivalent to: