LearnContact
Lesson 198 min read

Objects

A class defines a type, but objects are the actual instances created from that type. In this lesson, you will learn how to create objects, store independent data, call member functions, understand object memory, and work with multiple objects.

Introduction

In the previous lesson, you learned about classes. A class defines a new type by describing the data members and member functions associated with that type.

However, defining a class does not automatically create a specific student, account, product, or player. To represent individual entities, we create objects from the class type.

Class and Objects
Student Class
      │
      ├────► Rahul
      ├────► Amit
      └────► Priya

The Student class defines what student objects can contain and do. Individual objects can then store different values and represent different students.

The Main Idea

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

What is an Object?

An object is an instance of a type. When the type is a class, an object can contain its own non-static data member state and use the operations defined by the class.

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

// Object of type Student
Student student1;
Object Concept
Class Type: Student
        │
        ▼
Object: student1
┌──────────────────────┐
│ rollNumber           │
│ name                 │
└──────────────────────┘
TermMeaning
ClassDefines a user-defined type
ObjectAn instance of a type
Object StateValues stored in the object’s non-static data members
Object BehaviorOperations available through member functions
Simple Definition

An object is a specific instance created from a class type.

Why Do We Need Objects?

A class defines a type, but programs usually need specific instances with their own values. Objects provide those instances.

Without Objects

  • There are no individual class instances.
  • No per-object state exists.
  • Member functions have no specific object to operate on.
  • Different real-world entities cannot be represented as separate instances.

With Objects

  • Each instance can maintain its own state.
  • Member functions can operate on a specific object.
  • Multiple independent entities can be represented.
  • The same class definition can be reused many times.

Store State

Each object can store values in its own non-static data members.

Perform Operations

Member functions can be called for specific objects.

Represent Entities

Different objects can represent different students, accounts, products, or players.

Reuse Types

One class definition can be used to create many objects.

Build Systems

Applications can be composed from interacting objects.

Support OOP

Objects are central to object-oriented programming.

Real-World Analogy

Imagine a manufacturer designing a car. The design describes the structure and capabilities of the car, but the actual cars produced from that design are separate individual vehicles.

Car Analogy
              📐 Car Design
                    │
        ┌───────────┼───────────┐
        │           │           │
        ▼           ▼           ▼
     🚗 Car 1    🚗 Car 2    🚗 Car 3

The design corresponds to the class type. Each actual car corresponds to an object.

Real WorldC++
Car designClass
Individual carObject
Registration numberObject-specific data
Current fuel levelObject-specific state
Start or drive operationsMember functions
Define Class
Create Object
Give Object Its State
Use Object Operations

Characteristics of Objects

Created from a Type

An object is created using a class or another type.

Occupies Storage

An object requires storage appropriate for its type and lifetime.

Has State

An object can contain values in its non-static data members.

Uses Behavior

Member functions can operate on an object.

Independent Instances

Different objects can maintain different state.

Multiple Objects

Many objects can be created from the same class type.

Key Characteristics

  • An object is an instance of a type.
  • Objects have lifetimes.
  • Objects require storage according to their type and storage duration.
  • Each object has its own non-static data member state.
  • Member functions can operate on specific objects.
  • Multiple objects can be created from the same class.

Creating an Object

An object can be declared by writing the type name followed by the object name.

General Syntax
ClassName objectName;
Example
Student student1;
PartMeaning
StudentThe class type
student1The object name
;Ends the declaration
Declaration Breakdown
Student student1;
   │       │
   │       └──── Object Name
   │
   └──────────── Type Name

After the object is created, accessible members can be selected using the dot operator.

Using the Object
student1.rollNumber = 101;
student1.name = "Rahul";
student1.display();
Object Declaration

Student student1; declares an object named student1 whose type is Student.

Memory Allocation

A class definition describes a type. Defining the class itself does not create an object of that class.

Class Definition

  • Defines a type.
  • Describes data members.
  • Describes member functions.
  • Does not create a Student object.

Object Declaration

  • Creates an object.
  • The object has its own non-static data members.
  • Storage is provided according to its storage duration.
  • The object has a lifetime.
Class Definition
class Student
{
public:
    int rollNumber;
    std::string name;
};

// No Student object has been declared yet.
Object Declaration
Student student1;

// student1 is now an object of type Student.
Conceptual Object State
student1
┌────────────────────────┐
│ rollNumber             │
│ name                   │
└────────────────────────┘
Important Distinction

Defining a class defines a type. Declaring an object creates an instance of that type.

Creating Multiple Objects

A single class type can be used to create multiple objects.

Multiple Objects
Student student1;
Student student2;
Student student3;

Each object has its own non-static data members and can store different values.

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

student2.rollNumber = 102;
student2.name = "Amit";

student3.rollNumber = 103;
student3.name = "Priya";
Conceptual Object State
student1
┌──────────────────────┐
│ rollNumber = 101     │
│ name       = Rahul   │
└──────────────────────┘

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

student3
┌──────────────────────┐
│ rollNumber = 103     │
│ name       = Priya   │
└──────────────────────┘
ObjectrollNumbername
student1101Rahul
student2102Amit
student3103Priya
Independent State

Changing the non-static data members of one object does not automatically change those of another object.

Example 1: Creating an Object

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 class type.
  • student1 is declared as an object of type Student.
  • 101 is assigned to student1.rollNumber.
  • Rahul is assigned to student1.name.
  • The dot operator selects members of student1.
  • The values stored in student1 are displayed.
Output
101
Rahul
Define Student Type
Create student1
Assign rollNumber
Assign name
Display Object State

Example 2: Multiple Objects

Example 2
#include <iostream>
#include <string>

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

int main()
{
    Student student1;
    Student student2;

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

    student2.rollNumber = 102;
    student2.name = "Amit";

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

    return 0;
}

Explanation

  • student1 and student2 are separate objects of the same type.
  • student1 stores Rahul.
  • student2 stores Amit.
  • Each object maintains its own non-static data member values.
  • Reading student1.name does not read student2.name.
Output
Rahul
Amit
Independent Objects
Student Type
     │
     ├────► student1 ────► Rahul
     │
     └────► student2 ────► Amit
Same Type, Different State

Objects created from the same class type can store different values.

Example 3: Calling Member Functions

Objects can also be used to call accessible member functions.

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

class Student
{
public:
    std::string name;

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

int main()
{
    Student student1;

    student1.name = "Rahul";

    student1.display();

    return 0;
}

Explanation

  • student1 is created as an object of type Student.
  • Rahul is stored in student1.name.
  • student1.display() calls the display() member function for student1.
  • Inside display(), name refers to the name member of the current object.
  • The function displays the state belonging to student1.
Output
Student Name : Rahul
Create student1
Store Rahul
Call student1.display()
Member Function Uses student1 State
Display Result
Object-Specific Operation

A non-static member function called through an object works with that object.

Object Lifecycle

Every object has a lifetime. Its lifetime begins according to the rules for how the object is created and ends according to its storage duration and destruction rules.

Class Type Is Defined
Object Is Created
Object Lifetime Begins
Object State Is Initialized
Object Is Used
Member Functions Are Called
Object Lifetime Ends
Automatic Object Lifetime
int main()
{
    Student student1;

    student1.name = "Rahul";
    student1.display();

} // student1's lifetime ends here

In this example, student1 is a local automatic object. Its lifetime ends when execution leaves its scope.

Lifecycle
Enter Scope
     │
     ▼
Create Object
     │
     ▼
Object Lifetime Begins
     │
     ▼
Use Object
     │
     ▼
Leave Scope
     │
     ▼
Object Lifetime Ends
Lifecycle Depends on Creation

Not every object lives until the program ends. An object’s lifetime depends on how and where it is created.

Class vs Object

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

FeatureClassObject
DefinitionDefines a typeInstance of a type
ExampleStudentstudent1
PurposeDescribes structure and behaviorRepresents a specific instance
StateDefines which non-static data members existStores its own member values
CreationDefined using class syntaxDeclared or otherwise created from the type
QuantityOne type definition can be reusedMany objects can exist
Class and Objects
class Student
{
public:
    int rollNumber;
};

// Three objects
Student student1;
Student student2;
Student student3;
Relationship
Class Type: Student
        │
        ├────► Object: student1
        ├────► Object: student2
        └────► Object: student3
Remember

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

Real-World Applications

Objects can represent specific entities and components throughout software applications.

Banking Systems

Specific customers, accounts, transactions, and loans.

Education Systems

Individual students, teachers, courses, and exams.

Healthcare Systems

Specific patients, doctors, appointments, and records.

E-Commerce

Individual products, customers, carts, and orders.

Game Development

Specific players, enemies, weapons, and vehicles.

Transport Systems

Individual vehicles, drivers, routes, and bookings.

Application Objects
Banking Application
│
├── Account: account1
├── Account: account2
├── Customer: customer1
└── Transaction: transaction1

Advantages of Objects

Individual Instances

Objects can represent separate entities.

Independent State

Each object can maintain different member values.

Associated Operations

Member functions can operate on specific objects.

Reusable Types

The same class type can create many objects.

Better Modeling

Applications can represent meaningful entities and relationships.

OOP Foundation

Objects are central to object-oriented programming.

  • Represent individual entities.
  • Store independent object state.
  • Use member functions with specific objects.
  • Reuse one class type to create many instances.
  • Organize applications around meaningful concepts.
  • Support object-oriented program design.

Common Beginner Mistakes

Accessing a Non-Static Member Through the Class Name

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

Confusing the Type with an Instance

Student is the type, while student1 is an object of that type.

Using the Wrong Object

Each object has independent state, so access the object whose data you actually need.

Assuming Objects Share Non-Static Data

Changing one object’s non-static data members does not automatically change another object.

Reading Uninitialized Fundamental Members

Fundamental data members should be initialized before their values are read.

Access Through an Object
class Student
{
public:
    std::string name;
};

Student student1;

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

// ✅ Correct
student1.name = "Rahul";
Independent Objects
Student student1;
Student student2;

student1.name = "Rahul";
student2.name = "Amit";

// student1.name is still Rahul
// student2.name is still Amit
Initialize Fundamental Members
class Student
{
public:
    int rollNumber = 0;
};
Objects Are Independent

Do not assume that changing the state of one object automatically changes another object.

Best Practices

  • Use meaningful object names.
  • Use camelCase for ordinary local object names.
  • Create separate objects for separate entities.
  • Initialize object state before using it.
  • Use the correct object when accessing data.
  • Prefer member functions that preserve valid object state.
  • Avoid unnecessary global objects.
  • Keep object lifetimes as limited as practical.
  • Use constructors for proper initialization when appropriate.
  • Keep implementation details private in real class designs.
Meaningful Object Names
Student firstStudent;
BankAccount mainAccount;
Product selectedProduct;
Limited Scope
void processStudent()
{
    Student student;

    // Use student here.

} // Lifetime ends when the function scope ends
Initialize Objects Properly

The next lesson introduces constructors, which provide a structured way to initialize objects when they are created.

Frequently Asked Questions

What is an object?

An object is an instance of a type. For a class type, it can contain its own non-static data member state and use the class’s member functions.

What is the difference between a class and an object?

A class defines a type, while an object is a specific instance of that type.

Can one class create multiple objects?

Yes. Any number of objects can be created from the same class type, subject to program and resource limits.

Do different objects share their non-static data members?

No. Each object has its own non-static data members.

Which operator accesses members through an object?

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

Does defining a class create an object?

No. Defining a class defines a type. An object must be declared or otherwise created separately.

When does a local object’s lifetime end?

For an ordinary local automatic object, its lifetime normally ends when execution leaves its scope.

Can objects of the same class store different values?

Yes. Different objects can maintain different values in their non-static data members.

Can an object call member functions?

Yes. Accessible non-static member functions can be called through an object.

What happens when an object is created?

Storage is provided, the object’s lifetime begins according to the applicable rules, and initialization takes place.

Key Takeaways

  • An object is an instance of a type.
  • A class defines a user-defined type.
  • Defining a class does not automatically create an object.
  • Objects have lifetimes.
  • Each object has its own non-static data member state.
  • Multiple objects can be created from the same class type.
  • Different objects can store different values.
  • The dot operator accesses accessible members through an object.
  • Member functions can operate on specific objects.
  • Local automatic objects normally live until their scope ends.
  • Objects can represent individual entities in applications.
  • Objects are fundamental to object-oriented programming.

Summary

Objects are instances of types. When created from a class type, objects provide the actual instances that programs can use.

Each object can maintain its own non-static data member state. This allows multiple objects created from the same class to represent different entities and store different values.

Objects can access available members through the dot operator and call member functions that operate on their state.

Objects also have lifetimes. Local automatic objects normally exist until execution leaves their scope, while other kinds of objects follow different lifetime rules.

Now that you understand how objects are created and used, the next lesson will introduce constructors, which provide a structured way to initialize objects when their lifetime begins.

Next Lesson →

Constructors