How do I write constructors, destructors, and assignment operators in C++?

In C++, constructors, destructors, and assignment operators are special member functions that play essential roles in resource management and object lifecycle. Here's a brief overview along with examples of how to implement them.

Constructors

A constructor is a special member function that is called when an object of a class is instantiated. Its primary purpose is to initialize the object's properties.

Destructors

A destructor is called when an object goes out of scope or is explicitly deleted. It is used to free resources that the object may have acquired during its lifetime.

Assignment Operators

The assignment operator is used to copy the values from one object to another. If you do not define your own assignment operator, the compiler provides a default one.

Example

class Example { int *data; public: // Constructor Example(int value) { data = new int(value); } // Copy Constructor Example(const Example &other) { data = new int(*(other.data)); } // Destructor ~Example() { delete data; } // Assignment Operator Example& operator=(const Example &other) { if (this != &other) { delete data; // Free existing resource data = new int(*(other.data)); // Allocate new resource } return *this; } int getValue() const { return *data; } };

C++ Constructors Destructors Assignment Operators Object Lifecycle