Introduction
Hello Coders!
Constructors set the stage for creating objects, defining their properties, while Destructors gracefully conclude their lifecycle, releasing resources. In this exploration, we’ll delve into the pivotal role these elements play in crafting efficient, organized, and resource-aware C++ programs. ## Constructors and DestructorsConstructors are special member functions in a class that are called when an object of the class is created. They initialize the object’s data members or perform other setup tasks. Destructors, on the other hand, are called when an object is about to be destroyed, allowing for cleanup activities. Here’s an example of a class with a constructor and a destructor:
#include
#include
class Student {
public:
// Constructor
Student(std::string n, int a) : name(n), age(a) {
std::cout << "Constructor called for " << name << std::endl;
}
// Member function
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
// Destructor
~Student() {
std::cout << "Destructor called for " << name << std::endl;
}
private:
std::string name;
int age;
};
int main() {
// Creating objects invokes the constructor
Student student1("Alice", 20);
Student student2("Bob", 22);
// Calling member function
student1.displayInfo();
student2.displayInfo();
// Destructor is automatically called when objects go out of scope
return 0;
}
In this example, the Student
class has a constructor that initializes the name
and age
data members. The displayInfo
member function displays the student’s information. The destructor prints a message when the object is about to be destroyed.
Exercise: Write Classes with Constructors and DestructorsNow, let’s practice writing classes with constructors and destructors. For example:
#include
#include
class Book {
public:
// Constructor
Book(std::string t, std::string a) : title(t), author(a) {
std::cout << "Book constructor called for " << title << std::endl;
}
// Member function
void displayInfo() {
std::cout << "Title: " << title << ", Author: " << author << std::endl;
}
// Destructor
~Book() {
std::cout << "Book destructor called for " << title << std::endl;
}
private:
std::string title;
std::string author;
};
int main() {
// Creating objects invokes the constructor
Book book1("The Great Gatsby", "F. Scott Fitzgerald");
Book book2("To Kill a Mockingbird", "Harper Lee");
// Calling member function
book1.displayInfo();
book2.displayInfo();
// Destructor is automatically called when objects go out of scope
return 0;
}
Conclusion
Feel free to modify the Book
class and create additional objects. This exercise will help you gain hands-on experience with constructors and destructors in
C++. A solid grasp of Constructors and Destructors in C++ empowers you to sculpt well-organized and resource-efficient code, enhancing the lifecycle management of your objects. Happy coding!