Chapter 23 of 48

Classes & Objects

Up to now, our programs have been organised around functions: data lives in variables, and functions operate on it. This is called procedural programming. It works well for small programs, but in large ones, any function can modify any data, and it becomes hard to know who changed what.

Object-oriented programming (OOP) takes a different view: bundle the data and the functions that work on it into one unit, and control who can touch the data. In C++, that unit is the class.

In the Structures, Unions & Enums topic, we saw that a C++ struct can hold both data and functions. A class is the same idea, with one crucial addition: the ability to hide data from the outside world. In this topic, we'll learn how to define classes, create objects, control access, and write member functions properly.


What Are Classes and Objects?

A class is a user-defined type that describes a set of data (data members, also called attributes or fields) and the operations on that data (member functions, also called methods).

An object is an instance of a class: an actual variable of that class type, occupying memory and holding its own values for the data members.

The usual analogy: a class is the blueprint of a house; objects are the actual houses built from it. One blueprint, many houses, each with its own paint colour and furniture.

            class BankAccount   (blueprint: no memory for data yet)
          ┌──────────────────────────────┐
          │ data:      owner, balance    │
          │ functions: deposit, withdraw │
          └──────────────────────────────┘
                 │                 │
        creates  ▼                 ▼  creates
   ┌───────────────────┐   ┌───────────────────┐
   │ acc1              │   │ acc2              │
   │ owner   = "Asha"  │   │ owner   = "Ravi"  │
   │ balance = 3800    │   │ balance = 800     │
   └───────────────────┘   └───────────────────┘
        object 1                 object 2

Syntax

class ClassName
{
private:
    // data members (usually hidden)

public:
    // member functions (the interface)
};      // semicolon required

ClassName obj;        // create an object
obj.memberFunction(); // call a member function with the dot operator

Access Specifiers

Inside a class, the keywords public, private and protected decide who may access the members that follow them.

SpecifierAccessible from member functions of the classAccessible from derived classesAccessible from outside code (e.g. main())
publicYesYesYes
protectedYesYesNo
privateYesNoNo

Derived classes and protected belong to the Inheritance topic; for now, focus on public and private. An access specifier stays in effect until the next one. In a class, members are private by default.

Note: access control works per class, not per object. A member function of BankAccount may access the private members of any BankAccount object, not just its own.


A Complete Example: BankAccount

Let's model a bank account. The balance must never be changed carelessly, so we make it private and only allow changes through deposit() and withdraw(), which check the amount first.

#include <iostream>
#include <string>

class BankAccount
{
private:                          // hidden from code outside the class
    std::string owner = "Unknown";
    double balance = 0.0;

public:                           // the interface everyone can use
    void setOwner(const std::string& name)
    {
        owner = name;
    }

    void deposit(double amount)
    {
        if (amount <= 0)
        {
            std::cout << "Deposit must be positive\n";
            return;
        }
        balance += amount;
    }

    bool withdraw(double amount)
    {
        if (amount <= 0 || amount > balance)
        {
            std::cout << "Withdrawal of " << amount << " refused\n";
            return false;
        }
        balance -= amount;
        return true;
    }

    double getBalance() const
    {
        return balance;
    }

    void show() const
    {
        std::cout << owner << " has Rs. " << balance << '\n';
    }
};

int main()
{
    BankAccount acc1;              // an object of class BankAccount
    BankAccount acc2;              // another, completely separate object

    acc1.setOwner("Asha");
    acc1.deposit(5000);
    acc1.withdraw(1200);

    acc2.setOwner("Ravi");
    acc2.deposit(-50);             // rejected
    acc2.deposit(800);
    acc2.withdraw(1000);           // rejected: not enough money

    acc1.show();
    acc2.show();

    // acc1.balance = 1000000;     // error: 'balance' is private
    std::cout << "Asha's balance via getter: " << acc1.getBalance() << '\n';
    return 0;
}

Output:

Deposit must be positive
Withdrawal of 1000 refused
Asha has Rs. 3800
Ravi has Rs. 800
Asha's balance via getter: 3800

Step by step:

  1. BankAccount acc1; creates an object. Its members start with the values given by the default member initializers: owner = "Unknown", balance = 0.0. (In the next topic, Constructors & Destructors, we'll learn a better way to set up a new object.)

  2. acc1.deposit(5000) runs deposit() on acc1. Inside the function, balance means acc1's balance, so it becomes 5000. Then withdraw(1200) brings it to 3800.

  3. acc2 is a separate object with its own owner and balance. The invalid deposit of −50 and the withdrawal of 1000 (only 800 available) are both refused, so acc2 ends with 800.

  4. getBalance() lets outside code read the balance without being able to change it.

How does deposit() know whether to change acc1 or acc2? The compiler secretly passes the address of the calling object to every member function. That hidden pointer is called this, and it has its own topic: The this Pointer.

What Happens If We Touch a Private Member?

class BankAccount
{
private:
    double balance = 0.0;
public:
    double getBalance() const { return balance; }
};

int main()
{
    BankAccount acc;
    acc.balance = 1000000;
    return 0;
}

This does not compile. g++ 15 says:

main.cpp:12:9: error: ‘double BankAccount::balance’ is private within this context
   12 |     acc.balance = 1000000;
      |         ^~~~~~~
main.cpp:4:12: note: declared private here

The protection is checked at compile time, so it costs nothing at run time. (It also isn't a security feature: anyone with the source code could change private to public. It protects programmers from mistakes, not from attackers.)


Encapsulation and Data Hiding

Encapsulation means bundling data together with the functions that operate on it, inside one unit (the class).

Data hiding means restricting direct access to that data (using private), so it can only be changed through the class's public functions.

Why go to this trouble? Compare a plain struct with public data:

struct Account { double balance; };

Account a{500};
a.balance = -100000;     // nothing stops this

Every piece of code in the program can set the balance to anything, including a nonsense value. With the class version, the only ways to change balance are deposit() and withdraw(), and both check their input. This gives us three big benefits:

  • Valid state guaranteed. A rule like "balance is never negative" (called a class invariant) only needs to be enforced in a few member functions, not everywhere in the program.

  • Easier debugging. If the balance is wrong, the bug must be in one of a handful of member functions.

  • Freedom to change the implementation. We could later store the balance in paise as a long long instead of a double. As long as the public functions behave the same, code using the class doesn't change.

Functions like getBalance() are called getters (accessors) and functions like setOwner() are setters (mutators). Don't add a getter and setter for every member automatically, though. A setter that accepts anything (void setBalance(double b) { balance = b; }) gives away the very protection we wanted. Provide the operations that make sense for the type, like deposit() and withdraw().


Defining Member Functions Outside the Class

For short functions, defining them inside the class is fine. For larger classes, we usually only declare the functions inside the class and define them outside, using the scope resolution operator :: to say which class they belong to.

#include <iostream>

class Rectangle
{
private:
    double length = 1.0;
    double width = 1.0;

public:
    // declarations only (the "what")
    void setSize(double l, double w);
    double area() const;
    double perimeter() const;
    bool isSquare() const;
};

// definitions outside the class (the "how"), using ClassName::
void Rectangle::setSize(double l, double w)
{
    if (l > 0 && w > 0)
    {
        length = l;
        width = w;
    }
}

double Rectangle::area() const
{
    return length * width;
}

double Rectangle::perimeter() const
{
    return 2 * (length + width);
}

bool Rectangle::isSquare() const
{
    return length == width;
}

int main()
{
    Rectangle r;
    std::cout << std::boolalpha;            // print bools as true/false
    std::cout << "Default: area " << r.area() << ", square? " << r.isSquare() << '\n';

    r.setSize(4, 2.5);
    std::cout << "After setSize(4, 2.5): area " << r.area()
              << ", perimeter " << r.perimeter()
              << ", square? " << r.isSquare() << '\n';
    return 0;
}

Output:

Default: area 1, square? true
After setSize(4, 2.5): area 10, perimeter 13, square? false

double Rectangle::area() const reads as "the function area, which belongs to class Rectangle". Without Rectangle::, the compiler would think we're defining an ordinary global function called area, which can't see length and width.

Header and Source Files

In real projects, this split goes one step further. The class definition goes in a header file, and the member function definitions go in a source file:

rectangle.h     →  class Rectangle { ... declarations ... };
rectangle.cpp   →  #include "rectangle.h"
                   double Rectangle::area() const { ... }  (definitions)
main.cpp        →  #include "rectangle.h"
                   uses Rectangle

Users of the class only need to read the header to know what it can do, and when the how in rectangle.cpp changes, only that file is recompiled.

Defined inside the classDefined outside with ::
Implicitly inline (so it can live in a header without violating the one-definition rule). The one exception is a class defined in a C++20 named module.Not inline unless marked inline
Convenient for short getters and one-linersKeeps the class definition short and readable
Every file that includes the header sees the bodyBody can be hidden in a .cpp file

Remember from the Default Arguments & Inline Functions topic that inline is only a hint for optimisation; its main effect today is allowing the same definition in several files.


const Member Functions

You've seen const written after some member functions, like double getBalance() const.

A const member function promises not to modify the object it is called on. The compiler enforces this promise: assigning to a data member inside it is an error.

Why does it matter? Because a const object (or an object accessed through a const reference) can only call const member functions.

#include <iostream>

class Counter
{
private:
    int count = 0;
public:
    void increment() { count++; }          // modifies the object
    int get() const { return count; }      // promises not to modify
};

void report(const Counter& c)              // c is read-only here
{
    std::cout << "count = " << c.get() << '\n';   // OK: get() is const
    c.increment();                                // error
}

int main()
{
    Counter c;
    c.increment();
    report(c);
    return 0;
}

Compiler error (g++ 15):

main.cpp:15:16: error: passing ‘const Counter’ as ‘this’ argument discards qualifiers [-fpermissive]
   15 |     c.increment();                                // error
      |     ~~~~~~~~~~~^~
main.cpp:8:10: note:   in call to ‘void Counter::increment()’

report() takes a const Counter&, so it may only call functions that promise not to modify the counter. get() is fine; increment() is rejected. (The message mentions the this argument; we'll understand exactly why in The this Pointer.)

Rule of thumb: mark every member function that doesn't change the object as const. If you forget, your class can't be used through const references, which is how objects are usually passed.


Objects in Memory

Each object gets its own copy of the data members, but the member functions exist only once in the program's code, shared by all objects. Functions do not make an object bigger.

#include <iostream>

class Point
{
private:
    int x = 0;
    int y = 0;
public:
    void set(int newX, int newY) { x = newX; y = newY; }
    void print() const { std::cout << "(" << x << ", " << y << ")\n"; }
    int distanceSquared() const { return x * x + y * y; }
};

class Empty
{
};

int main()
{
    std::cout << "sizeof(Point) = " << sizeof(Point) << '\n';   // two ints
    std::cout << "sizeof(Empty) = " << sizeof(Empty) << '\n';

    Point a, b;
    a.set(3, 4);
    b = a;            // copies x and y
    b.set(10, 20);    // changes only b

    a.print();
    b.print();
    std::cout << "a.distanceSquared() = " << a.distanceSquared() << '\n';
    return 0;
}

Output (g++ on x86-64):

sizeof(Point) = 8
sizeof(Empty) = 1
(3, 4)
(10, 20)
a.distanceSquared() = 25
  • sizeof(Point) is 8: just the two ints. The three member functions take no space in the object. (Classes with virtual functions do carry a hidden pointer; that's in Polymorphism & Virtual Functions.)

  • sizeof(Empty) is 1, not 0, so that two different objects always have different addresses.

  • b = a; copies every data member, as with structs. After that, a and b are independent: changing b doesn't affect a.

Memory                                   Code (one copy)
┌─────────────┐  ┌─────────────┐         ┌─────────────────────────┐
│ a: x=3, y=4 │  │ b: x=10,y=20│         │ Point::set(int, int)    │
└─────────────┘  └─────────────┘         │ Point::print()          │
     8 bytes          8 bytes            │ Point::distanceSquared()│
                                         └─────────────────────────┘

Arrays of Objects and Objects as Parameters

Objects behave like any other variables: we can make arrays of them, pass them to functions, and return them. The parameter-passing rules from the Functions and References topics apply unchanged.

#include <iostream>
#include <string>

class Student
{
private:
    std::string name;
    int marks = 0;
public:
    void set(const std::string& n, int m) { name = n; marks = m; }
    void addBonus(int b) { marks += b; }
    int getMarks() const { return marks; }
    const std::string& getName() const { return name; }
};

void bonusByValue(Student s)       // works on a copy
{
    s.addBonus(10);
}

void bonusByReference(Student& s)  // works on the original
{
    s.addBonus(10);
}

int main()
{
    Student batch[3];              // array of 3 objects
    batch[0].set("Asha", 72);
    batch[1].set("Ravi", 85);
    batch[2].set("Meena", 64);

    bonusByValue(batch[0]);        // no effect on batch[0]
    bonusByReference(batch[2]);    // batch[2] gets +10

    const Student* top = &batch[0];
    for (const Student& s : batch)
    {
        std::cout << s.getName() << ": " << s.getMarks() << '\n';
        if (s.getMarks() > top->getMarks())
            top = &s;
    }
    std::cout << "Topper: " << top->getName() << '\n';
    return 0;
}

Output:

Asha: 72
Ravi: 85
Meena: 74
Topper: Ravi
  • Student batch[3]; creates three objects, each with an empty name and marks = 0.

  • bonusByValue(batch[0]) receives a copy, so Asha still has 72. bonusByReference(batch[2]) works on the original, so Meena goes from 64 to 74.

  • top->getMarks() uses the arrow operator on a pointer to an object, exactly as with structs.

  • getName() returns a const std::string&: the caller can read the name without copying it, but can't modify it.

Pass objects by const& when the function only reads them, by & when it must modify them, and by value only when it needs its own copy.


struct vs class

In C++, struct and class are almost identical. Both can have private members, member functions, constructors and inheritance. The only difference is the default access level.

#include <iostream>

struct S { int value = 1; };   // members public by default
class  C { int value = 2; };   // members private by default

int main()
{
    S s;
    C c;
    std::cout << s.value << '\n';   // OK
    std::cout << c.value << '\n';   // error: private
    return 0;
}

Compiler error:

main.cpp:11:20: error: ‘int C::value’ is private within this context
   11 |     std::cout << c.value << ‘\n’;   // error: private
      |                    ^~~~~
Pointstructclass
Default member accesspublicprivate
Default inheritancepublicprivate
Everything elseSameSame
Conventional useSimple data bundles with no rules to protect (a Point, a config record)Types with invariants and hidden data (a BankAccount)

The C++ Core Guidelines suggest: use class if the type has an invariant (some rule its data must obey); use struct if the members can vary independently.


Common Mistakes

  • Forgetting the semicolon after the class's closing brace.

  • Forgetting ClassName:: when defining a member function outside the class. The compiler then sees a global function and complains that the data members are "not declared in this scope".

  • Forgetting const on getters, which makes them unusable on const objects and const& parameters.

  • Making all data public, or adding unchecked setters for everything, which throws away encapsulation.

  • Leaving data members uninitialized. Without default member initializers (or constructors), int and double members of a local object hold garbage.

  • Passing large objects by value and then wondering why the original didn't change (or why the program is slow).

  • Writing Point p(); to create an object. That declares a function named p returning a Point! Write Point p; or Point p{};.


Interview / GATE Questions

1. What is the difference between a class and an object?

A class is a type: a description of data members and member functions. It occupies no memory for data by itself. An object is an instance of a class: it occupies memory and holds its own values for the data members. One class can have many objects.

2. What is encapsulation? How does C++ support it?

Encapsulation is bundling data and the functions that operate on it into one unit, and hiding the internal details. C++ supports it with classes (bundling) and access specifiers (private, protected, public) that control which code may access each member.

3. What is sizeof of a class with one int, one char and five non-virtual member functions, on a typical 64-bit system?

8. Member functions take no space in objects. The int (4) and char (1) need 5 bytes, rounded up to 8 because the class's alignment is 4.

4. Can a member function access private members of another object of the same class?

Yes. Access control in C++ is per class, not per object. For example, a member function bool isRicherThan(const BankAccount& other) const can read other.balance directly.

5. What is a const member function? Can a non-const object call it?

A member function declared with const after its parameter list. It cannot modify the object's data members (except those marked mutable). Both const and non-const objects can call a const member function, but const objects can call only const member functions.

6. What is the difference between struct and class in C++?

Only the default access: struct members and base classes are public by default, class ones are private by default. By convention, struct is used for simple data bundles and class for types with invariants.


Summary

  • A class bundles data members and member functions into a new type; an object is an instance of that type.

  • private members are accessible only inside the class; public members form its interface. protected is for derived classes. Class members are private by default.

  • Encapsulation and data hiding let a class guarantee its own invariants, such as a balance that is never negative.

  • Member functions can be defined inside the class (implicitly inline) or outside using ClassName::function.

  • Mark member functions that don't modify the object as const; only those can be called on const objects.

  • Each object has its own data members; member functions are shared and don't add to sizeof.

  • struct and class differ only in default access (public vs private).