SrcForge

Lesson 28

Classes and Objects

Covers class and object syntax, access specifiers, member functions, constructors, parameterized constructors, the this pointer, and private members.

Lesson content

What are classes and objects?

A class is a user-defined blueprint that defines the properties (data members) and behaviors (member functions) of an object. An object is an instance of a class. It occupies memory and can access the class's data and functions.

Imagine a car factory: the blueprint of a car represents a class, and every car manufactured using that blueprint is an object. Each car has its own values but follows the same blueprint.

Why do classes exist?

  • Grouping related data and functions together
  • Improving code organization
  • Encouraging code reuse
  • Supporting Object-Oriented Programming principles

Real-world use cases

  • Banking systems
  • Student management systems
  • E-commerce applications
  • Game development
  • Hospital management systems
  • Inventory systems
  • Mobile and desktop applications

Prerequisites

  • Variables
  • Data types
  • Functions
  • Structures
  • Basic C++ syntax

What is a class?

A class defines the structure of an object.

class ClassName
{
    // Data members

    // Member functions
};

class Student
{
public:
    int id;
    string name;

    void display()
    {
        cout << id << " " << name;
    }
};
  • Student is the class
  • id and name are data members
  • display() is a member function

What is an object?

An object is created from a class.

Student student1;

// Each object has its own copy of the data members.

Access specifiers

Access specifiers control the visibility of class members.

  • public: accessible inside the class, outside the class, and in derived classes
  • private: accessible inside the class only
  • protected: accessible inside the class and in derived classes, but not outside
class Student
{
private:
    int age;

public:
    string name;
};

Member functions

Member functions define the behavior of a class.

class Student
{
public:
    void greet()
    {
        cout << "Welcome!";
    }
};

Student s;

s.greet();

Constructors

A constructor is a special member function that is automatically called when an object is created.

class Student
{
public:
    Student()
    {
        cout << "Object Created";
    }
};

this pointer

Inside a member function, this refers to the current object.

class Student
{
public:
    int age;

    void setAge(int age)
    {
        this->age = age;
    }
};
  • this->age refers to the data member
  • age refers to the function parameter

Example 1: Creating a class and object

#include <iostream>
#include <string>
using namespace std;

class Student
{
public:

    int id;

    string name;
};

int main()
{
    Student student;

    student.id = 101;

    student.name = "Alice";

    cout << student.id << endl;

    cout << student.name << endl;

    return 0;
}

// Output:
// 101
// Alice

Example 2: Member function

#include <iostream>
#include <string>
using namespace std;

class Student
{
public:

    string name;

    void display()
    {
        cout << "Student: " << name << endl;
    }
};

int main()
{
    Student student;

    student.name = "John";

    student.display();

    return 0;
}

Example 3: Constructor

#include <iostream>
using namespace std;

class Rectangle
{
public:

    int length;

    int width;

    Rectangle()
    {
        length = 10;

        width = 5;
    }

    int area()
    {
        return length * width;
    }
};

int main()
{
    Rectangle rectangle;

    cout << rectangle.area();

    return 0;
}

// Output: 50

Example 4: Parameterized constructor

#include <iostream>
#include <string>
using namespace std;

class Employee
{
public:

    string name;

    double salary;

    Employee(string employeeName, double employeeSalary)
    {
        name = employeeName;

        salary = employeeSalary;
    }

    void display()
    {
        cout << name << endl;

        cout << salary << endl;
    }
};

int main()
{
    Employee employee("David", 55000.0);

    employee.display();

    return 0;
}

Example 5: Using private members

#include <iostream>
using namespace std;

class BankAccount
{
private:

    double balance;

public:

    void deposit(double amount)
    {
        balance += amount;
    }

    void displayBalance()
    {
        cout << "Balance: " << balance << endl;
    }

    BankAccount()
    {
        balance = 0.0;
    }
};

int main()
{
    BankAccount account;

    account.deposit(1000);

    account.displayBalance();

    return 0;
}

Common mistakes and pitfalls

  • Making all data members public. Fix: keep data private and provide public member functions when appropriate
  • Forgetting to initialize data members. Fix: initialize members using constructors
  • Accessing private members directly. Fix: use public getters/setters or other public methods
  • Writing large classes with too many responsibilities. Fix: follow the Single Responsibility Principle
  • Forgetting to mark read-only member functions as const. Fix: use const when a member function doesn't modify the object

Best practices

  • Keep data members private to enforce encapsulation
  • Initialize objects using constructors rather than assigning values later
  • Use meaningful class and member names
  • Keep classes focused on a single responsibility
  • Mark member functions as const when they don't modify the object's state
  • Prefer initializer lists in constructors for efficient member initialization

When not to use this

  • A simple function is sufficient
  • You're storing only a few unrelated variables
  • The added abstraction makes a very small program harder to understand
  • A struct with public data is more appropriate for plain data objects

Summary

  • A class is a blueprint for creating objects
  • An object is an instance of a class
  • Classes combine data members and member functions
  • Use access specifiers (public, private, protected) to control access
  • Constructors automatically initialize objects
  • The this pointer refers to the current object
  • Encapsulation improves security and maintainability
  • Well-designed classes make programs modular and reusable

Frequently asked questions

What is the difference between a class and an object?

A class is a blueprint or template that defines properties and behaviors and does not occupy memory for instance data by itself. An object is an instance of a class, occupies memory, and contains actual values.

Why are classes important in C++?

Classes support Object-Oriented Programming, making programs more modular, reusable, maintainable, and easier to understand.

What is the difference between a class and a struct?

The primary difference is the default access level: members and inheritance default to private in a class, while they default to public in a struct. Otherwise, they support almost the same language features in C++.

Why should data members be private?

Keeping data private protects an object's internal state from unintended modification and enforces encapsulation, one of the core principles of Object-Oriented Programming.

What is a constructor?

A constructor is a special member function that has the same name as the class and is automatically called when an object is created. It is primarily used to initialize the object's data members.