LearnContact
Lesson 1810 min read

Classes

As programs become larger, managing data and functions separately becomes difficult. In this lesson, you will learn how C++ uses classes to group related data and functions into a single unit, forming the foundation of Object-Oriented Programming.

Introduction

In the previous lesson, you learned about pointers. So far, you have worked with variables, arrays, functions, strings, references, and pointers. These concepts allow programs to store data and perform operations, but larger applications need a better way to organize related information and behavior.

Consider a Student Management System. Each student may have a roll number, name, age, and marks. The system may also need to display student details, calculate percentages, and update records.

Student Information
Student
├── Roll Number
├── Name
├── Age
├── Marks
├── Display Details
└── Calculate Percentage

Without classes, related data and functions may be scattered throughout the program. As the application grows, this makes the code harder to understand, maintain, and extend.

The Solution

C++ provides classes to group related data and functions into a single user-defined type.

What is a Class?

A class is a user-defined type that can group data members and member functions into a single unit.

A class describes the structure and behavior that objects created from that class can have.

Class Concept
Class: Student
│
├── Data
│   ├── rollNumber
│   └── name
│
└── Behavior
    └── display()
Class ComponentPurpose
Data MembersStore the state or properties of an object
Member FunctionsDefine operations or behavior associated with the class
Simple Definition

A class defines a new type that can contain both data and functions.

Why Do We Need Classes?

Classes help organize programs around meaningful concepts. Instead of keeping related variables and functions separate, a class places them together under one type.

Without Classes

  • Related data may remain scattered.
  • Functions may need many separate parameters.
  • Managing multiple related entities becomes difficult.
  • Code organization becomes harder as programs grow.
  • Protecting internal data becomes more difficult.

With Classes

  • Related data and behavior stay together.
  • Programs can model meaningful entities.
  • Multiple independent objects can be created.
  • Implementation details can be controlled.
  • Code becomes easier to organize and extend.

Organization

Related data and functions can be grouped into one type.

Object Creation

A class can be used to create multiple independent objects.

Data Control

Access specifiers can control how members are accessed.

Reusability

The same class definition can be reused to create many objects.

Maintainability

Related code is easier to locate, understand, and modify.

OOP Foundation

Classes are central to object-oriented programming in C++.

Real-World Analogy

Imagine an architect designing houses. Before construction begins, the architect creates a blueprint.

Blueprint Analogy
              📐 House Blueprint
                      │
          ┌───────────┼───────────┐
          │           │           │
          ▼           ▼           ▼
      🏠 House 1   🏠 House 2   🏠 House 3

The blueprint is not an actual house. It describes the structure that houses created from it should follow.

Similarly, a class defines a type, while objects are instances created from that type.

Real WorldC++
BlueprintClass
HouseObject
Rooms and dimensionsData members
Actions performed in the houseMember functions
Define Class
Class Describes Structure
Create Objects
Each Object Has Its Own State

Characteristics of a Class

User-Defined Type

A class allows programmers to define new types.

Groups Members

A class can contain data members and member functions.

Creates Objects

Objects can be created from the class type.

Controls Access

Access specifiers control how members can be used.

Reusable Definition

One class definition can create many objects.

Models Concepts

Classes can represent concepts such as students, accounts, products, and players.

Key Characteristics

  • A class is a user-defined type.
  • It can combine data and functions.
  • It can be used to create objects.
  • Each object can maintain its own state.
  • Access to members can be controlled.
  • The same class can be reused throughout a program.

Class Structure

A class commonly contains data members and member functions.

1. Data Members

Variables declared as members of a class. They represent the state or properties associated with an object.

2. Member Functions

Functions declared as members of a class. They define operations associated with the class.

Class Components
class Student
{
public:
    // Data Members
    int rollNumber;
    std::string name;

    // Member Function
    void display()
    {
        // Behavior
    }
};
ComponentExamplePurpose
Data MemberrollNumberStores object state
Data MembernameStores object state
Member Functiondisplay()Defines behavior

General Syntax

Class Syntax
class ClassName
{
public:
    // Data Members

    // Member Functions
};

Understanding the Syntax

  • class is the keyword used to define a class.
  • ClassName is the name of the new type.
  • The class body is enclosed in curly braces.
  • public is an access specifier.
  • Members declared after public: can be accessed from outside the class when using an object.
  • A semicolon is required after the closing brace of a class definition.
Student Class
class Student
{
public:
    int rollNumber;
    std::string name;

    void display()
    {
        // Function body
    }
};
Syntax PartMeaning
classKeyword used to define a class
StudentName of the class
public:Access specifier
rollNumberData member
nameData member
display()Member function
;Required after the class definition
Do Not Forget the Semicolon

A class definition must end with a semicolon after the closing brace.

Example 1: Creating a Class

Example 1
#include <iostream>
#include <string>

class Student
{
public:
    int rollNumber;
    std::string name;
};

int main()
{
    Student student1;

    student1.rollNumber = 101;
    student1.name = "Rahul";

    std::cout << student1.rollNumber << std::endl;
    std::cout << student1.name;

    return 0;
}

Step-by-Step Explanation

  • Student defines a new class type.
  • The class contains rollNumber and name as data members.
  • Student student1; creates an object named student1.
  • student1.rollNumber accesses the rollNumber member of student1.
  • student1.name accesses the name member of student1.
  • Values are assigned to the members.
  • The stored values are displayed.
Output
101
Rahul
Object State
student1
┌──────────────────────┐
│ rollNumber = 101     │
│ name       = Rahul   │
└──────────────────────┘
Object Creation

Student student1; creates an object whose type is Student.

Accessing Members

For an object, accessible non-static members can be selected using the dot operator.

General Syntax
object.member
Examples
student1.rollNumber;
student1.name;
student1.display();
ExpressionMeaning
student1The object
.Member access operator
rollNumberSelected data member
display()Selected member function
Choose Object
Use Dot Operator
Select Accessible Member
Read, Modify, or Call
Dot Operator

Use the dot operator to access accessible members through an object.

Example 2: Member Function

A class can contain functions in addition to data. Functions associated with a class are called member functions.

Example 2
#include <iostream>

class Student
{
public:
    void display()
    {
        std::cout << "Welcome to C++";
    }
};

int main()
{
    Student student1;

    student1.display();

    return 0;
}

Explanation

  • Student defines a class.
  • display() is a public member function.
  • student1 is an object of type Student.
  • student1.display() calls the member function for student1.
  • The function displays the message.
Output
Welcome to C++
Create student1
Call student1.display()
Enter Member Function
Execute Function Body
Return to main()

Example 3: Data Members and Member Function Together

Member functions can work with the data members of the object for which they are called.

Example 3
#include <iostream>
#include <string>

class Student
{
public:
    int rollNumber;
    std::string name;

    void display()
    {
        std::cout << "Roll Number : "
                  << rollNumber << std::endl;

        std::cout << "Name : "
                  << name;
    }
};

int main()
{
    Student student1;

    student1.rollNumber = 101;
    student1.name = "Rahul";

    student1.display();

    return 0;
}

Explanation

  • The class contains two data members.
  • The class also contains the display() member function.
  • student1 stores its own rollNumber and name values.
  • student1.display() calls display() for student1.
  • Inside the member function, rollNumber and name refer to the members of the current object.
  • The values belonging to student1 are displayed.
Output
Roll Number : 101
Name : Rahul
Object and Behavior
student1
┌────────────────────────┐
│ rollNumber = 101       │
│ name       = Rahul     │
│                        │
│ display()              │
└────────────────────────┘
          │
          ▼
Displays student1's data
Current Object

When a non-static member function is called through an object, it works with that object.

Memory Representation

Each object has its own state represented by its non-static data members.

Multiple Objects
Student student1;
Student student2;

student1.rollNumber = 101;
student1.name = "Rahul";

student2.rollNumber = 102;
student2.name = "Priya";
Conceptual Object Memory
student1
┌──────────────────────┐
│ rollNumber = 101     │
│ name       = Rahul   │
└──────────────────────┘

student2
┌──────────────────────┐
│ rollNumber = 102     │
│ name       = Priya   │
└──────────────────────┘

Changing the state of student1 does not automatically change the state of student2. They are separate objects.

ObjectrollNumbername
student1101Rahul
student2102Priya
Each Object Has Independent State

Objects created from the same class share the same type definition, but each object can store different values in its non-static data members.

Program Execution Flow

Program Starts
Class Definition Is Available
Create Object
Object Receives Its State
Assign Data Members
Call Member Function
Member Function Uses Object Data
Display Result
Program Ends

The class defines the type. Objects are then created from that type, given their own state, and used to access members or call member functions.

Class vs Object

A class and an object are related, but they are not the same thing.

FeatureClassObject
DefinitionDefines a typeInstance of a class type
RoleDescribes structure and behaviorRepresents a specific instance
ExampleStudentstudent1
Data StateDefines which data members existContains its own non-static data member values
QuantityDefined once as a typeMany objects can be created
Class and Objects
class Student
{
public:
    int rollNumber;
};

// Objects
Student student1;
Student student2;
Student student3;
Relationship
Student Class
     │
     ├────► student1
     ├────► student2
     └────► student3
Main Difference

A class defines a type. An object is an instance of that type.

Real-World Applications

Classes can model entities and concepts in many kinds of software.

Banking Systems

Account, Customer, Transaction, and Loan.

Education Systems

Student, Teacher, Course, and Exam.

E-Commerce

Product, Customer, Cart, and Order.

Healthcare Systems

Patient, Doctor, Appointment, and MedicalRecord.

Game Development

Player, Enemy, Weapon, and Vehicle.

Transport Systems

Vehicle, Driver, Route, and Booking.

Application Model
E-Commerce Application
│
├── Product
├── Customer
├── Cart
├── Order
└── Payment

Advantages of Classes

Better Organization

Related data and functions can be placed together.

Clear Modeling

Classes can represent meaningful concepts in the program.

Reusable Types

One class can be used to create many objects.

Controlled Access

Access specifiers can restrict direct access to implementation details.

Easier Maintenance

Related implementation can be organized in one place.

OOP Support

Classes support object-oriented design and advanced OOP features.

  • Group related data and behavior.
  • Create reusable user-defined types.
  • Create multiple independent objects.
  • Improve program organization.
  • Control access to members.
  • Provide a foundation for object-oriented programming.
  • Make larger applications easier to structure.

Common Beginner Mistakes

Forgetting the Semicolon

A class definition must end with a semicolon.

Accessing a Non-Static Member Through the Class Name

Ordinary non-static members belong to objects and should be accessed through an object.

Forgetting About Default Private Access

Members of a class are private by default unless another access specifier is used.

Confusing Class and Object

The class defines the type, while an object is an instance of that type.

Using Uninitialized Fundamental Data Members

Fundamental data members should be given valid initial values before they are read.

Forgetting the Semicolon
// ❌ Incorrect
class Student
{
}

// ✅ Correct
class Student
{
};
Accessing a Member
class Student
{
public:
    std::string name;
};

Student student1;

// ❌ Incorrect for a non-static member
// Student.name;

// ✅ Correct
student1.name = "Rahul";
Default Private Access
class Student
{
    int rollNumber; // private by default
};
Public Member
class Student
{
public:
    int rollNumber;
};
Class Members Are Private by Default

Unlike a struct, members declared in a class before any access specifier are private by default.

Best Practices

  • Use meaningful class names such as Student, BankAccount, and Product.
  • Use PascalCase for class names.
  • Keep related data and behavior together.
  • Give each class a clear responsibility.
  • Avoid placing unrelated responsibilities in one class.
  • Prefer controlled access to internal data instead of making everything public.
  • Initialize object state properly.
  • Use meaningful names for data members and member functions.
  • Keep member functions focused on clear tasks.
  • Design classes around meaningful program concepts.
Meaningful Class Name
class BankAccount
{
    // Account-related members
};
Focused Responsibility
class Student
{
    // Student-related state
    // Student-related behavior
};
Do Not Make Everything Public

Public data members are useful for first examples, but real classes commonly keep implementation details private and provide controlled operations through member functions.

Frequently Asked Questions

What is a class?

A class is a user-defined type that can contain data members and member functions.

What is an object?

An object is an instance of a type. For a class type, each object can have its own state.

What is a data member?

A data member is a variable declared as a member of a class.

What is a member function?

A member function is a function declared as a member of a class.

Which operator is used to access members through an object?

The dot operator is used to access accessible members through an object.

Can one class create multiple objects?

Yes. Multiple independent objects can be created from the same class type.

Do different objects share the same data values?

Each object has its own non-static data members, so different objects can store different values.

Are class members public by default?

No. Members of a class are private by default.

Why is a semicolon required after a class definition?

The C++ grammar requires a semicolon after a class definition.

Are classes used only in object-oriented programs?

No. Classes are a general C++ language feature, although they are central to object-oriented design.

Key Takeaways

  • A class defines a user-defined type.
  • Classes can group data members and member functions.
  • An object is an instance of a class type.
  • One class can be used to create multiple objects.
  • Each object has its own non-static data member state.
  • Member functions define operations associated with a class.
  • The dot operator accesses accessible members through an object.
  • A class definition must end with a semicolon.
  • Class members are private by default.
  • Access specifiers control member accessibility.
  • Classes help organize larger programs.
  • Classes are fundamental to object-oriented programming in C++.

Summary

Classes allow C++ programs to define new types that combine related data and behavior.

A class can contain data members that represent state and member functions that define operations. Objects are instances created from the class type, and each object can maintain its own state.

Accessible members can be selected through an object using the dot operator. Member functions can work directly with the data belonging to the object for which they are called.

Classes improve organization, provide controlled access to implementation details, support reusable types, and form an important foundation for object-oriented programming.

Now that you understand what a class defines, the next lesson will focus more deeply on objects: how they are created, how multiple objects maintain independent state, and how object lifetime works.

Next Lesson →

Objects