Skip to content

Module 5 · Classes and Objects — topic 1 of 5

Classes and Objects

A class bundles data and the functions that operate on it. Learn member variables, member functions, access specifiers, const member functions and the this pointer.

Beginner 15 min read·Lesson 17 of 40 in C++ Programming

Learning objectives

  • Define a class with private data and public member functions
  • Create objects and call member functions
  • Use const member functions and the this pointer

Definition

A class is a user-defined type that groups data members and member functions; an object is an instance of a class with its own copy of the non-static data members.

Introduction

Procedural programs pass data to functions. Object-oriented programs put the data and the functions together: a BankAccount object knows its balance and how to deposit into it. This makes it impossible to put the data into an invalid state from outside.

Why it matters

Classes are the core of C++ and of object-oriented design taught in every B.Tech curriculum.

Encapsulated classes make large programs maintainable: you can change the inside without breaking the code that uses it.

Detailed explanation

Members are private by default in a class. Public member functions form the class's interface; private data is reachable only through them.

Member functions are defined inside the class (implicitly inline) or outside using the scope operator: double Account::balance() const { ... }.

A const member function promises not to modify the object; only const functions can be called on const objects or through const references.

Inside a member function, this is a pointer to the current object. Writing this->x disambiguates a member from a parameter with the same name.

Each object has its own data members; member functions are shared code.

Syntax

C++
class Account {
public:
void deposit(double amount);
double balance() const { return balance_; }
private:
double balance_ = 0.0;
};
void Account::deposit(double amount) {
if (amount > 0) balance_ += amount;
}
  • End the class definition with a semicolon.
  • A trailing underscore on members is a common naming convention.
  • Use . on objects and -> on pointers to objects.

Code examples

A simple class

C++
#include <iostream>
class Counter {
public:
void increment() { ++count_; }
int value() const { return count_; }
private:
int count_ = 0;
};
int main() {
Counter a, b;
a.increment();
a.increment();
b.increment();
std::cout << a.value() << ' ' << b.value() << '\n';
return 0;
}
Output
2 1

Each object has its own count_.

this and name clashes

C++
#include <iostream>
class Box {
public:
void set_width(double width) { this->width = width; }
double get_width() const { return width; }
private:
double width = 0;
};
int main() {
Box b;
b.set_width(4.5);
std::cout << b.get_width() << '\n';
return 0;
}
Output
4.5

More examples

A bank account that protects its balance

C++
#include <iostream>
#include <string>
class Account {
public:
explicit Account(std::string owner) : owner_(std::move(owner)) {}
bool deposit(double amount) {
if (amount <= 0) return false;
balance_ += amount;
return true;
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) return false;
balance_ -= amount;
return true;
}
double balance() const { return balance_; }
const std::string& owner() const { return owner_; }
private:
std::string owner_;
double balance_ = 0.0;
};
int main() {
Account acc("Asha");
acc.deposit(1000);
std::cout << std::boolalpha << acc.withdraw(1500) << ' ' << acc.withdraw(400) << '\n';
std::cout << acc.owner() << ": " << acc.balance() << '\n';
return 0;
}
Output
false true
Asha: 600

Step-by-step explanation

  • The constructor stores the owner's name; it is covered in the next lesson.
  • deposit and withdraw validate before changing the balance.
  • The withdrawal of 1500 fails because only 1000 is available.
  • Outside code cannot write acc.balance_ = -5; the balance can only change through the checked functions.

Expected output

Running “A bank account that protects its balance” prints exactly:

TextOutput
false true
Asha: 600

Practical applications

  • GUI toolkits model windows and buttons as classes.
  • Game engines model players, enemies and items as objects.
  • Banking software encapsulates accounts so balances can't be edited directly.

Best practices

  • Keep data private and expose behaviour, not fields.
  • Mark every function that doesn't modify the object const.
  • Validate inputs in member functions to maintain the object's invariants.

Common mistakes

Accessing private members from outside

Avoid

Account a("x");
a.balance_ = 100;

Prefer

Account a("x");
a.deposit(100);

Private members are accessible only inside the class; use the public interface.

Calling a non-const function on a const object

Avoid

void show(const Counter& c) { c.increment(); }

Prefer

void show(const Counter& c) { std::cout << c.value(); }

Only const member functions may be called through a const reference.

Important notes

  • Static data members are shared by all objects of a class: static int count;.
  • Classes can be forward-declared (class Account;) when only pointers or references are needed.

Key takeaways

  • A class bundles private data with public member functions.
  • Each object holds its own data.
  • const member functions don't modify the object; this points to it.

Try it yourself

  1. 1
    Write a Rectangle class with width/height, area() and perimeter().
  2. 2
    Write a Stopwatch class with start, stop and elapsed that tracks seconds passed in as arguments.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerBy default, members of a `class` are…
  • BeginnerWhat is printed?
  • BeginnerWhat does `const` after a member function declaration mean (e.g. `int get() const;`)?
Practise this topic