Object and Class
By Notes Vandar
2.1 Concept of Object and Class
In C++, the concepts of objects and classes are fundamental to object-oriented programming (OOP). These concepts allow developers to model real-world entities and relationships in a structured and organized way.
1. Class
A class is a user-defined data type that serves as a blueprint for creating objects. It encapsulates data (attributes) and functions (methods) that operate on that data. A class defines the properties and behaviors that the objects created from it will have.
Key Features of Classes:
- Encapsulation: Classes bundle data and methods that manipulate that data into a single unit, promoting data hiding and abstraction.
- Reusability: Classes can be reused in different parts of a program or in different programs, which reduces code duplication and enhances maintainability.
Syntax:
// Access specifiers: public, private, protected
public:
// Data members (attributes)
// Member functions (methods)
};
Example:
#include <iostream>
using namespace std;
class Dog {
public:
// Data members
string name;
int age;
// Member function
void bark() {
cout << name << ” says Woof!” << endl;
}
};
In this example, Dog
is a class with two data members (name
and age
) and a member function (bark()
).
2. Object
An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. Objects have their own states and can interact with other objects through methods defined in their class.
Key Features of Objects:
- State: The current values of an object’s attributes.
- Behavior: The functions that can be called on the object, defined by its class.
Creating an Object: To create an object, you declare it using the class name as a type.
Example:
// Creating an object of the Dog class
Dog myDog;
// Setting attributes
myDog.name = “Buddy”;
myDog.age = 3;
// Calling member function
myDog.bark(); // Output: Buddy says Woof!
return 0;
}
In this example, myDog
is an object of the class Dog
. We set its attributes and call the bark()
method to display a message.
3. Access Specifiers
Classes in C++ can have different access levels for their members:
- Public: Members declared as public can be accessed from outside the class.
- Private: Members declared as private can only be accessed within the class itself. This provides a way to protect sensitive data.
- Protected: Members declared as protected can be accessed within the class and by derived classes.
Example:
class Cat {
private:
string name; // private member
public:
void setName(string n) { // public member function
name = n;
}
void meow() {
cout << name << ” says Meow!” << endl;
}
};
In this example, name
is a private member, which means it cannot be accessed directly from outside the Cat
class. The setName()
function allows setting the name of the cat.
2.2 Data Members and Member Functions in C++
In C++, data members and member functions are fundamental components of a class. They allow classes to encapsulate data and provide functionality related to that data, which is essential for object-oriented programming. Let’s define and explore these concepts in detail.
1. Data Members
Data members are variables defined within a class that hold the state or attributes of the objects created from that class. They represent the properties of an object and can be of any data type, including built-in types (like int
, float
, etc.) and user-defined types (like classes, structs, etc.).
Characteristics of Data Members:
- They are associated with a specific class and are accessible through the objects of that class.
- They can have different access specifiers (public, private, protected), which determine the visibility and accessibility of the data members.
Example:
public:
// Data members
string model;
int year;
float price;
};
Car
class has three data members: model
, year
, and price
, which define the characteristics of a car object.2. Member Functions
Member functions are functions defined within a class that operate on the data members of that class. They provide the functionality to manipulate or access the object’s data. Member functions can perform actions such as setting data, retrieving data, or performing computations based on the data members.
Characteristics of Member Functions:
- They have access to the class’s data members and can manipulate them.
- They can also have different access specifiers (public, private, protected), determining how they can be accessed.
Example:
class Car {
public:
// Data members
string model;
int year;
float price;
// Member function to display car details
void displayDetails() {
cout << “Model: ” << model << endl;
cout << “Year: ” << year << endl;
cout << “Price: $” << price << endl;
}
// Member function to set car details
void setDetails(string m, int y, float p) {
model = m;
year = y;
price = p;
}
};
In this example, the Car
class has two member functions: displayDetails()
and setDetails()
. The setDetails()
function allows you to set the values of the data members, while the displayDetails()
function displays the values of the data members.
3. Accessing Data Members and Member Functions
You access data members and member functions using the object of the class. The dot operator (.
) is used for this purpose.
Example:
int main() {
Car myCar; // Create an object of Car class
// Set car details using member function
myCar.setDetails(“Toyota Camry”, 2020, 24000.00);
// Display car details using member function
myCar.displayDetails();
return 0;
}
In this example, an object myCar
of the Car
class is created. The setDetails()
member function is called to set the values of the data members, and the displayDetails()
function is called to print those values.
2.3 Creating Objects and Accessing Member Functions in C++
In C++, creating objects and accessing their member functions is fundamental to utilizing the features of object-oriented programming. This section will guide you through the process of creating an object from a class and how to access its member functions to manipulate or retrieve data.
1. Defining a Class
First, let’s define a class with data members and member functions.
Example Class Definition:
#include <iostream>
using namespace std;
class Rectangle {
private:
// Data members
float length;
float width;
public:
// Member function to set dimensions
void setDimensions(float l, float w) {
length = l;
width = w;
}
// Member function to calculate area
float calculateArea() {
return length * width;
}
// Member function to display dimensions
void displayDimensions() {
cout << “Length: ” << length << “, Width: ” << width << endl;
}
};
2. Creating an Object
To use the Rectangle
class, you need to create an object of that class. An object is an instance of the class, which can have its own unique values for the data members.
Creating an Object:
int main() {
// Creating an object of Rectangle class
Rectangle myRectangle;
// Setting dimensions using member function
myRectangle.setDimensions(5.0, 3.0);
// Displaying dimensions using member function
myRectangle.displayDimensions(); // Output: Length: 5, Width: 3
// Calculating and displaying the area using member function
float area = myRectangle.calculateArea();
cout << “Area: ” << area << endl; // Output: Area: 15
return 0;
}
In this main()
function:
- An object named
myRectangle
is created from theRectangle
class. - The
setDimensions()
member function is called to set the length and width of the rectangle. - The
displayDimensions()
member function is called to print the dimensions of the rectangle. - The
calculateArea()
member function is called to compute and display the area of the rectangle.
3. Accessing Member Functions
Member functions can be accessed using the dot operator (.
) followed by the function name. This allows you to perform operations on the object and manipulate its data.
Example of Accessing Member Functions:
2.4 Making Outer Functions Inline in C++
In C++, the inline
keyword is used to suggest to the compiler that it should attempt to expand the function’s code at each call site, rather than performing a traditional function call. This can improve performance by reducing function call overhead, especially for small, frequently called functions.
1. Defining Inline Functions
You can define an inline function in two main ways: within a class definition or outside the class. When defined outside a class, you can still make it inline.
1.1 Inline Function Inside a Class: When you define a function inside the class definition, it is implicitly treated as an inline function.
Example:
public:
// Inline function defined inside the class
inline int square(int x) {
return x * x;
}
};
inline
keyword.Example:
#include <iostream>
using namespace std;
class Math {
public:
// Declaration of an inline function
inline int cube(int x);
};
// Definition of the inline function outside the class
inline int Math::cube(int x) {
return x * x * x;
}
In this example, cube
is declared and defined as an inline function outside the Math
class.
2. Advantages of Inline Functions
- Performance Improvement: Reduces the overhead associated with function calls.
- Code Clarity: Inline functions can improve code readability by keeping related code together.
- Compiler Optimization: The compiler has the option to optimize the inline function, which can lead to better performance.
3. Disadvantages of Inline Functions
- Code Size Increase: If an inline function is called many times, it may lead to code bloat, increasing the overall size of the binary.
- Limited Debugging: Debugging inline functions can be more challenging since their actual code is expanded at each call site.
- Compiler Discretion: The compiler is free to ignore the
inline
request; it may decide not to inline a function for various reasons, such as its complexity.
4. Using Inline Functions
You can use the inline function just like any other function in your program. Here’s how you might use both the inline functions defined inside and outside the class.
Example:
int main() {
Math mathObj;
// Using the inline function defined inside the class
int num = 5;
cout << “Square of ” << num << ” is: ” << mathObj.square(num) << endl;
// Using the inline function defined outside the class
cout << “Cube of ” << num << ” is: ” << mathObj.cube(num) << endl;
return 0;
}
Output:
Cube of 5 is: 125
2.5 Arrays Within a Class in C++
In C++, you can define arrays as data members within a class. This allows you to create objects that can hold multiple values of the same type, encapsulated within the class. Using arrays within a class can be beneficial for organizing related data and performing operations on that data using member functions.
1. Defining an Array in a Class
You can declare an array as a data member in a class like any other data type. Here’s a simple example to demonstrate how to define and use arrays within a class.
Example Class with an Array:
#include <iostream>
using namespace std;
class Student {
private:
string name;
int grades[5]; // Array to hold grades for 5 subjects
public:
// Member function to set student details
void setDetails(string studentName, int studentGrades[]) {
name = studentName;
for (int i = 0; i < 5; i++) {
grades[i] = studentGrades[i];
}
}
// Member function to display student details
void displayDetails() {
cout << “Name: ” << name << endl;
cout << “Grades: “;
for (int i = 0; i < 5; i++) {
cout << grades[i] << ” “;
}
cout << endl;
}
// Member function to calculate average grade
float calculateAverage() {
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += grades[i];
}
return static_cast<float>(sum) / 5; // Calculate average
}
};
In this example, the Student
class has:
- A private
name
data member. - An array
grades
that can hold grades for five subjects. - Member functions to set details, display details, and calculate the average grade.
2. Using the Class with Array Data Members
Now, let’s create an object of the Student
class, set the values of the array, and call the member functions.
Example Usage:
int main() {
Student student1;
string name = “Alice”;
int grades[5] = {85, 90, 78, 92, 88}; // Example grades
// Set student details using member function
student1.setDetails(name, grades);
// Display student details using member function
student1.displayDetails(); // Output student details
// Calculate and display average grade
float average = student1.calculateAverage();
cout << “Average Grade: ” << average << endl;
return 0;
}
Output:
3. Accessing Array Elements
You can access and manipulate the elements of the array using member functions. In this example, the setDetails()
function initializes the array with the provided grades, while the displayDetails()
function prints all grades in the array.
4. Important Points
- Array Size: The size of the array must be a constant value known at compile time.
- Initialization: Arrays can be initialized using a loop or by passing an existing array to a member function.
- Dynamic Arrays: For dynamic sizing, consider using pointers and dynamic memory allocation (using
new
anddelete
) or standard library containers likestd::vector
.
2.6 Array of Objects in C++
In C++, you can create arrays of objects to manage multiple instances of a class efficiently. This allows you to store and manipulate a collection of related objects using array indexing. Arrays of objects are particularly useful when dealing with collections of data that share the same structure and behavior.
1. Defining a Class
Let’s start by defining a class. In this example, we will create a Book
class that holds information about books.
Example Class Definition:
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
float price;
public:
// Member function to set book details
void setDetails(string bookTitle, string bookAuthor, float bookPrice) {
title = bookTitle;
author = bookAuthor;
price = bookPrice;
}
// Member function to display book details
void displayDetails() {
cout << “Title: ” << title << “, Author: ” << author << “, Price: $” << price << endl;
}
};
In this example, the Book
class has three private data members (title
, author
, and price
) and two public member functions: setDetails()
and displayDetails()
.
2. Creating an Array of Objects
You can create an array of Book
objects to hold multiple book instances. Here’s how to do it:
Example of Using an Array of Objects:
int main() {
const int NUM_BOOKS = 3; // Number of books
Book books[NUM_BOOKS]; // Array of Book objects
// Setting details for each book
books[0].setDetails(“The Catcher in the Rye”, “J.D. Salinger”, 10.99);
books[1].setDetails(“To Kill a Mockingbird”, “Harper Lee”, 12.49);
books[2].setDetails(“1984”, “George Orwell”, 14.99);
// Displaying details of each book
cout << “Book Details:” << endl;
for (int i = 0; i < NUM_BOOKS; i++) {
books[i].displayDetails();
}
return 0;
}
In this main()
function:
- We define a constant
NUM_BOOKS
to specify the number of books. - An array named
books
is created to holdNUM_BOOKS
instances of theBook
class. - We use the
setDetails()
member function to set the title, author, and price for each book. - Finally, we loop through the array and call the
displayDetails()
member function for each book to print their details.
3. Example Output
When you run the above code, the output will be:
Title: The Catcher in the Rye, Author: J.D. Salinger, Price: $10.99
Title: To Kill a Mockingbird, Author: Harper Lee, Price: $12.49
Title: 1984, Author: George Orwell, Price: $14.99
4. Important Points to Consider
- Initialization: You can initialize each object in the array using loops or by directly assigning values as shown.
- Memory Management: When using static arrays, the size must be known at compile time. For dynamic arrays, consider using pointers or containers from the Standard Template Library (STL), like
std::vector
. - Accessing Members: Use the dot operator (
.
) to access member functions and data members of each object in the array.
2.7 Static Data Members and Static Functions in C++
In C++, static data members and static member functions are features that allow you to share data and functions across all instances of a class. They belong to the class itself rather than any individual object, which means they are shared among all instances of that class. This can be useful for managing data that should be common across all objects.
1. Static Data Members
A static data member is shared by all instances of a class. This means there is only one copy of the static data member for the entire class, regardless of how many objects of the class are created.
Key Characteristics:
- Declared using the
static
keyword. - Initialized outside the class definition.
- Accessed using the class name or through an object of the class.
Example of Static Data Member:
#include <iostream>
using namespace std;
class Employee {
private:
static int employeeCount; // Static data member
string name;
public:
// Constructor to increment employee count
Employee(string employeeName) {
name = employeeName;
employeeCount++;
}
// Static function to get the employee count
static int getEmployeeCount() {
return employeeCount;
}
};
// Definition and initialization of static data member
int Employee::employeeCount = 0;
int main() {
Employee emp1(“Alice”);
Employee emp2(“Bob”);
Employee emp3(“Charlie”);
// Accessing static member function to get employee count
cout << “Total Employees: ” << Employee::getEmployeeCount() << endl; // Output: Total Employees: 3
return 0;
}
In this example:
- The
Employee
class has a static data memberemployeeCount
that keeps track of the total number ofEmployee
instances created. - The constructor increments
employeeCount
each time a new object is created. - The static member function
getEmployeeCount()
is used to return the value ofemployeeCount
.
2. Static Member Functions
A static member function can access static data members and can be called without an instance of the class. It cannot access non-static data members or non-static member functions directly.
Key Characteristics:
- Declared using the
static
keyword. - Can be called using the class name or through an object.
- Does not have a
this
pointer, so it cannot access instance members directly.
Example of Static Member Function:
#include <iostream>
using namespace std;
class Counter {
private:
static int count; // Static data member
public:
// Constructor to increment count
Counter() {
count++;
}
// Static member function to get the count
static int getCount() {
return count;
}
};
// Definition and initialization of static data member
int Counter::count = 0;
int main() {
Counter c1;
Counter c2;
Counter c3;
// Calling static member function to get the count
cout << “Total Count: ” << Counter::getCount() << endl; // Output: Total Count: 3
return 0;
}
In this example:
- The
Counter
class has a static data membercount
that tracks how manyCounter
objects have been created. - The static member function
getCount()
returns the value ofcount
. - You can call
getCount()
without needing an instance ofCounter
.
3. Important Points to Remember
- Initialization: Static data members must be initialized outside the class definition.
- Memory Management: Static members are allocated memory when the program starts and deallocated when the program ends, regardless of how many instances of the class are created.
- Use Cases: Static data members and functions are useful for keeping track of information that is common across all instances, such as counts, settings, or configuration parameters.
2.8 Friends Functions
In C++, a friend function is a function that is given access to the private and protected members of a class. It is not a member of the class but can access its private and protected data. Friend functions can be useful for certain operations that require access to the internal state of the class without being a member of it.
1. Characteristics of Friend Functions
- Not a Member: Friend functions are not member functions of the class. They are defined outside the class.
- Access Privileges: They have access to the private and protected members of the class for which they are declared as friends.
- Declared in the Class: To make a function a friend, you must declare it within the class using the
friend
keyword. - Function Signature: The friend function should match the declared signature to be able to access the class members.
2. Example of Friend Function
Here’s a simple example to illustrate how friend functions work:
Example Code:
#include <iostream>
using namespace std;
class Box {
private:
double length;
double width;
double height;
public:
// Constructor to initialize the box dimensions
Box(double l, double w, double h) : length(l), width(w), height(h) {}
// Friend function declaration
friend void displayVolume(Box b); // Friend function
};
// Definition of friend function
void displayVolume(Box b) {
double volume = b.length * b.width * b.height; // Accessing private members
cout << “Volume of the box: ” << volume << endl;
}
int main() {
Box box(3.5, 4.0, 5.0); // Creating an object of Box
displayVolume(box); // Calling friend function to display volume
return 0;
}
Output:
In this example:
- The
Box
class has three private data members:length
,width
, andheight
. - The
displayVolume()
function is declared as a friend of theBox
class. - Inside
displayVolume()
, we can access the private members ofBox
directly to calculate and display the volume.
3. Use Cases for Friend Functions
- Overloading Operators: Friend functions are commonly used for operator overloading, allowing operators to access the private members of the class.
- Interacting with Multiple Classes: When two or more classes need to collaborate closely and share their private data, friend functions can facilitate this interaction.
- Non-Member Functions: When it makes more sense to keep a function outside the class while still needing access to its internal data.
4. Important Points to Remember
- Friendship is Not Mutual: If class A declares class B as a friend, class B does not automatically have access to the private members of class A.
- Friend Functions Are Not Inherited: If a class is inherited from a base class, the derived class does not inherit friend functions.
- Design Considerations: Use friend functions judiciously, as they can break encapsulation by exposing class internals. They should be used when absolutely necessary to maintain clean and maintainable code.
2.9 Concept of Constructor and Destructor in C++
In C++, constructors and destructors are special member functions that are automatically invoked when an object of a class is created or destroyed, respectively. They play a crucial role in resource management and object lifecycle control.
1. Constructor
A constructor is a special member function that is executed when an object of the class is created. Its main purpose is to initialize the object’s data members and allocate resources if needed.
Key Characteristics of Constructors:
- Name: The constructor has the same name as the class.
- No Return Type: Constructors do not have a return type, not even
void
. - Overloading: You can overload constructors to create objects in different ways.
- Default Constructor: A constructor that takes no arguments. It initializes the object with default values.
- Parameterized Constructor: A constructor that takes arguments to initialize the object with specific values.
- Copy Constructor: A constructor that creates a new object as a copy of an existing object.
Example of Constructor:
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
// Default constructor
Rectangle() {
length = 1.0;
width = 1.0;
}
// Parameterized constructor
Rectangle(double l, double w) {
length = l;
width = w;
}
// Member function to calculate area
double area() {
return length * width;
}
};
int main() {
Rectangle rect1; // Calls default constructor
Rectangle rect2(3.5, 2.0); // Calls parameterized constructor
cout << “Area of rect1: ” << rect1.area() << endl; // Output: Area of rect1: 1
cout << “Area of rect2: ” << rect2.area() << endl; // Output: Area of rect2: 7
return 0;
}
In this example:
Rectangle
has both a default constructor and a parameterized constructor.- The default constructor initializes the dimensions to 1.0, while the parameterized constructor initializes them to the values provided.
2. Destructor
A destructor is a special member function that is executed when an object of the class is destroyed. Its primary purpose is to release resources that were allocated during the lifetime of the object, such as memory or file handles.
Key Characteristics of Destructors:
- Name: The destructor has the same name as the class, prefixed with a tilde (
~
). - No Return Type: Destructors do not have a return type and cannot take parameters.
- Called Automatically: Destructors are called automatically when an object goes out of scope or is deleted.
- Only One Destructor: A class can have only one destructor.
Example of Destructor:
#include <iostream>
using namespace std;
class Resource {
public:
Resource() {
cout << “Resource allocated.” << endl;
}
~Resource() {
cout << “Resource released.” << endl;
}
};
int main() {
Resource res; // Constructor is called (Resource allocated)
// Destructor will be called automatically when res goes out of scope
return 0; // Resource released
}
In this example:
- The
Resource
class has a constructor that allocates a resource and a destructor that releases it. - The output demonstrates that the resource is allocated when the object is created and released when it goes out of scope.
3. Importance of Constructors and Destructors
- Resource Management: Constructors and destructors help manage resources (e.g., memory, file handles) efficiently, preventing memory leaks and ensuring proper cleanup.
- Object Initialization: Constructors allow for proper initialization of objects, ensuring that they are in a valid state before use.
- Object Cleanup: Destructors ensure that resources are released when objects are no longer needed, helping maintain system stability.
2.10 Empty, Parameterized and Copy constructor
In C++, constructors are special member functions that are invoked when an object of a class is created. There are different types of constructors, including empty (default) constructors, parameterized constructors, and copy constructors. Each serves a specific purpose in initializing objects of a class.
1. Empty (Default) Constructor
An empty constructor, also known as a default constructor, is a constructor that does not take any parameters. It initializes objects with default values.
Key Features:
- Can be defined with no parameters.
- Initializes data members with default values.
Example of Empty Constructor:
#include <iostream>
using namespace std;
class Box {
private:
double length;
double width;
public:
// Default constructor
Box() {
length = 1.0; // Default value for length
width = 1.0; // Default value for width
}
// Function to calculate area
double area() {
return length * width;
}
};
int main() {
Box box; // Calls the default constructor
cout << “Area of the box: ” << box.area() << endl; // Output: Area of the box: 1
return 0;
}
In this example, the Box
class has a default constructor that initializes the length and width to 1.0.
2. Parameterized Constructor
A parameterized constructor is a constructor that takes arguments to initialize an object with specific values. This allows for more flexibility in object creation.
Key Features:
- Takes parameters to set initial values for data members.
- Can be overloaded to create objects in different ways.
Example of Parameterized Constructor:
#include <iostream>
using namespace std;
class Box {
private:
double length;
double width;
public:
// Parameterized constructor
Box(double l, double w) {
length = l; // Initialize length with parameter value
width = w; // Initialize width with parameter value
}
// Function to calculate area
double area() {
return length * width;
}
};
int main() {
Box box1(3.5, 2.0); // Calls the parameterized constructor
Box box2(5.0, 4.0); // Calls the parameterized constructor
cout << “Area of box1: ” << box1.area() << endl; // Output: Area of box1: 7
cout << “Area of box2: ” << box2.area() << endl; // Output: Area of box2: 20
return 0;
}
In this example, the Box
class has a parameterized constructor that allows for the initialization of length and width with specific values during object creation.
3. Copy Constructor
A copy constructor is a special constructor that creates a new object as a copy of an existing object. It is used when an object needs to be initialized with another object of the same class.
Key Features:
- Takes a reference to an object of the same class as its parameter.
- Used for deep copying of objects, especially when dynamic memory is involved.
Example of Copy Constructor:
#include <iostream>
using namespace std;
class Box {
private:
double length;
double width;
public:
// Parameterized constructor
Box(double l, double w) : length(l), width(w) {}
// Copy constructor
Box(const Box &b) {
length = b.length; // Copy length from existing object
width = b.width; // Copy width from existing object
}
// Function to calculate area
double area() {
return length * width;
}
};
int main() {
Box box1(3.5, 2.0); // Calls parameterized constructor
Box box2 = box1; // Calls copy constructor
cout << “Area of box1: ” << box1.area() << endl; // Output: Area of box1: 7
cout << “Area of box2 (copy of box1): ” << box2.area() << endl; // Output: Area of box2: 7
return 0;
}
In this example:
- The
Box
class has a parameterized constructor and a copy constructor. - When
box2
is created as a copy ofbox1
, the copy constructor initializesbox2
‘s length and width with the values frombox1
.
4. Summary of Constructors
Type of Constructor | Purpose |
---|---|
Empty (Default) | Initializes objects with default values. |
Parameterized | Initializes objects with specific values. |
Copy | Creates a new object as a copy of an existing object. |
2.11 Define Destructor in C++
A destructor is a special member function in C++ that is automatically invoked when an object of a class is destroyed. The primary purpose of a destructor is to release resources that were acquired during the lifetime of the object, such as memory, file handles, or network connections.
Key Features of Destructors
- Name: The destructor has the same name as the class but is preceded by a tilde (
~
). For example, if your class is namedMyClass
, the destructor would be defined as~MyClass()
. - No Parameters: Destructors do not take any parameters and do not return any value. They cannot be overloaded.
- Called Automatically: The destructor is called automatically when an object goes out of scope or is explicitly deleted using the
delete
operator. - One Per Class: A class can have only one destructor, and it cannot be overloaded.
- Scope of Destructor: The destructor is executed in the reverse order of the constructor, meaning that the destructor for derived classes is called before the destructor for the base class when an object is destroyed.
Purpose of Destructors
- Resource Cleanup: Destructors are primarily used for resource management. When an object is destroyed, its destructor ensures that any memory or resources allocated during the object’s lifetime are properly released. This helps prevent memory leaks and ensures that resources are not wasted.
- Execution of Cleanup Code: You can include any additional cleanup logic that needs to be executed when an object is no longer needed.
Example of Destructor
Here’s a simple example to illustrate how a destructor works in C++:
#include <iostream>
using namespace std;
class Resource {
private:
int* data; // Pointer to dynamically allocated memory
public:
// Constructor
Resource(int size) {
data = new int[size]; // Allocate memory
cout << “Resource allocated.” << endl;
}
// Destructor
~Resource() {
delete[] data; // Free the allocated memory
cout << “Resource released.” << endl;
}
};
int main() {
Resource res(10); // Calls constructor (Resource allocated)
// Automatically calls destructor (Resource released) when ‘res’ goes out of scope
return 0;
}
Output:
Resource released.
In this example:
- The
Resource
class allocates memory for an array of integers in its constructor. - The destructor (
~Resource()
) releases the allocated memory usingdelete[]
, ensuring there are no memory leaks. - When the object
res
goes out of scope at the end ofmain
, the destructor is automatically called, and the message “Resource released.” is printed.