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
├── Roll Number
├── Name
├── Age
├── Marks
├── Display Details
└── Calculate PercentageWithout 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.
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: Student
│
├── Data
│ ├── rollNumber
│ └── name
│
└── Behavior
└── display()| Class Component | Purpose |
|---|---|
| Data Members | Store the state or properties of an object |
| Member Functions | Define operations or behavior associated with the class |
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.
📐 House Blueprint
│
┌───────────┼───────────┐
│ │ │
▼ ▼ ▼
🏠 House 1 🏠 House 2 🏠 House 3The 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 World | C++ |
|---|---|
| Blueprint | Class |
| House | Object |
| Rooms and dimensions | Data members |
| Actions performed in the house | Member functions |
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 Student
{
public:
// Data Members
int rollNumber;
std::string name;
// Member Function
void display()
{
// Behavior
}
};| Component | Example | Purpose |
|---|---|---|
| Data Member | rollNumber | Stores object state |
| Data Member | name | Stores object state |
| Member Function | display() | Defines behavior |
General 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.
class Student
{
public:
int rollNumber;
std::string name;
void display()
{
// Function body
}
};| Syntax Part | Meaning |
|---|---|
| class | Keyword used to define a class |
| Student | Name of the class |
| public: | Access specifier |
| rollNumber | Data member |
| name | Data member |
| display() | Member function |
| ; | Required after the class definition |
A class definition must end with a semicolon after the closing brace.
Example 1: Creating a Class
#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.
101
Rahulstudent1
┌──────────────────────┐
│ rollNumber = 101 │
│ name = Rahul │
└──────────────────────┘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.
object.memberstudent1.rollNumber;
student1.name;
student1.display();| Expression | Meaning |
|---|---|
| student1 | The object |
| . | Member access operator |
| rollNumber | Selected data member |
| display() | Selected member function |
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.
#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.
Welcome to C++Example 3: Data Members and Member Function Together
Member functions can work with the data members of the object for which they are called.
#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.
Roll Number : 101
Name : Rahulstudent1
┌────────────────────────┐
│ rollNumber = 101 │
│ name = Rahul │
│ │
│ display() │
└────────────────────────┘
│
▼
Displays student1's dataWhen 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.
Student student1;
Student student2;
student1.rollNumber = 101;
student1.name = "Rahul";
student2.rollNumber = 102;
student2.name = "Priya";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.
| Object | rollNumber | name |
|---|---|---|
| student1 | 101 | Rahul |
| student2 | 102 | Priya |
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
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.
| Feature | Class | Object |
|---|---|---|
| Definition | Defines a type | Instance of a class type |
| Role | Describes structure and behavior | Represents a specific instance |
| Example | Student | student1 |
| Data State | Defines which data members exist | Contains its own non-static data member values |
| Quantity | Defined once as a type | Many objects can be created |
class Student
{
public:
int rollNumber;
};
// Objects
Student student1;
Student student2;
Student student3;Student Class
│
├────► student1
├────► student2
└────► student3A 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.
E-Commerce Application
│
├── Product
├── Customer
├── Cart
├── Order
└── PaymentAdvantages 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
A class definition must end with a semicolon.
Ordinary non-static members belong to objects and should be accessed through an object.
Members of a class are private by default unless another access specifier is used.
The class defines the type, while an object is an instance of that type.
Fundamental data members should be given valid initial values before they are read.
// ❌ Incorrect
class Student
{
}
// ✅ Correct
class Student
{
};class Student
{
public:
std::string name;
};
Student student1;
// ❌ Incorrect for a non-static member
// Student.name;
// ✅ Correct
student1.name = "Rahul";class Student
{
int rollNumber; // private by default
};class Student
{
public:
int rollNumber;
};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.
class BankAccount
{
// Account-related members
};class Student
{
// Student-related state
// Student-related behavior
};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.