Constructors & Destructors in C++

0
373
Constructors & Destructors in C++

In C++, understanding how objects are initialized and destroyed is fundamental to mastering Object-Oriented Programming (OOP). Two special member functions—Constructors and Destructors—play a crucial role in managing object lifecycles, memory, and resource control. In this in-depth guide by Kamlesh Singad, part of the Code With Kamlesh series, we will cover both the theory and practical implementation of constructors and destructors to help you write clean, efficient, and bug-free code.

Introduction to Constructors & Destructors in C++

Constructors and destructors are special class functions automatically invoked when an object is created and destroyed, respectively. They allow you to initialize class members when an object is instantiated and to release resources or perform cleanup tasks when an object’s lifecycle ends.

These functions enhance the robustness of your code and simplify memory management, especially when dealing with dynamic memory or file operations.

Also Read: Operators in C/C++: Arithmetic, Logical, Relational & Bitwise

Constructors & Destructors in C++

What is a Constructor in C++?

A constructor is a special member function that initializes an object. It has the same name as the class and no return type, not even void.

class Student {
public:
    Student() {
        cout << "Constructor Called!" << endl;
    }
};

Whenever an object of the class is created, the constructor runs automatically.

Characteristics of Constructors

  • Same name as the class.
  • No return type.
  • Can be overloaded.
  • Called automatically when an object is created.
  • Can accept arguments to set initial values.

Types of Constructors in C++

Default Constructor

A constructor with no parameters.

class Book {
public:
    Book() {
        cout << "Default Constructor" << endl;
    }
};

Parameterized Constructor

Allows initialization with custom values.

class Book {
public:
    string title;
    Book(string t) {
        title = t;
    }
};
Book b1("C++ Fundamentals");

Constructor Overloading

You can define multiple constructors with different parameter lists.

image 27
class Rectangle {
public:
    int length, breadth;
    Rectangle() {
        length = 0;
        breadth = 0;
    }
    Rectangle(int l, int b) {
        length = l;
        breadth = b;
    }
};

Also Read: Understanding Data Types and Variables in C/C++

Constructors & Destructors in C++

Copy Constructor

Initializes a new object using another object of the same type.

class Box {
public:
    int length;
    Box(int l) {
        length = l;
    }
    Box(const Box &b) {
        length = b.length;
    }
};

Constructor Initialization List

Used to initialize members before the constructor body executes.

class Employee {
public:
    int id;
    string name;
    Employee(int i, string n) : id(i), name(n) {
        cout << "Employee created" << endl;
    }
};

This approach is efficient and preferred for initializing const or reference members.

Constructors in Inheritance

Constructors in base classes are called before those in derived classes.

class Person {
public:
    Person() {
        cout << "Person Constructor" << endl;
    }
};

class Student : public Person {
public:
    Student() {
        cout << "Student Constructor" << endl;
    }
};

What is a Destructor in C++?

A destructor is a special function invoked automatically when an object goes out of scope or is deleted.

class Sample {
public:
    ~Sample() {
        cout << "Destructor Called!" << endl;
    }
};

Destructors are essential for releasing memory and other resources.

Also Read: Structure of a C/C++ Program: A Comprehensive Guide

Characteristics of Destructors

  • Same name as the class, preceded by a tilde ~.
  • No parameters and no return type.
  • Cannot be overloaded.
  • Called automatically.
  • Defined only once per class.

Virtual Destructors

Virtual destructors are necessary in polymorphic base classes to ensure derived class destructors are called.

class Base {
public:
    virtual ~Base() {
        cout << "Base Destructor" << endl;
    }
};

class Derived : public Base {
public:
    ~Derived() {
        cout << "Derived Destructor" << endl;
    }
};

When deleting an object through a base class pointer, the destructor of the derived class will also be called if the base destructor is virtual.

Destructors in Inheritance

Destructors are called in reverse order—first the derived class, then the base class.

class A {
public:
    ~A() {
        cout << "Destructor A" << endl;
    }
};

class B : public A {
public:
    ~B() {
        cout << "Destructor B" << endl;
    }
};

Practical Example: Constructor and Destructor in a File Class

#include <iostream>
#include <fstream>
using namespace std;

class FileHandler {
    ofstream file;
public:
    FileHandler(string filename) {
        file.open(filename);
        cout << "File opened.\n";
    }
    ~FileHandler() {
        file.close();
        cout << "File closed.\n";
    }
};
int main() {
    FileHandler fh("log.txt");
    return 0;
}

Best Practices for Constructors & Destructors

  • Always initialize member variables in constructors.
  • Use constructor initialization lists where possible.
  • Always define a destructor when using dynamic memory (new or malloc).
  • Make destructors virtual when using polymorphism.
  • Avoid complex logic in constructors or destructors.
  • Ensure exception safety in both.
Constructors & Destructors in C++

Common Mistakes to Avoid

  • Forgetting to define a destructor in classes managing dynamic memory.
  • Not making base class destructors virtual in polymorphic scenarios.
  • Using default constructor but not providing one after defining parameterized constructors.
  • Returning values from constructors (not allowed).
  • Forgetting to close file or free memory in destructors.

FAQs

What is the main purpose of a constructor?
To initialize objects at the time of their creation.

Can constructors be overloaded in C++?
Yes, you can have multiple constructors with different parameters.

What is a copy constructor?
It creates a new object as a copy of an existing object.

When is a destructor called in C++?
When an object goes out of scope or is deleted.

Can you overload a destructor?
No, destructors cannot be overloaded.

Why use virtual destructors?
To ensure proper destruction of derived class objects through base class pointers.

Conclusion

Understanding Constructors & Destructors in C++ is vital for mastering object-oriented development. They define how objects are born and how they gracefully exit your program, managing resources efficiently and reliably. In this tutorial by Kamlesh Singad under the Code With Kamlesh initiative, you’ve explored both the theoretical underpinnings and hands-on coding examples of these core C++ concepts.

As you move forward in your C++ journey, continue practicing these patterns to write maintainable and robust software with confidence.

LEAVE A REPLY

Please enter your comment!
Please enter your name here