TalentJR

Lesson 7

Constructors & Destructors

Control object creation and cleanup

1What Are Constructors?✨

Constructors are special functions in a class that are called when an object is created. They help initialize the object's properties. If you don't define a constructor, C++ provides a default one.

2Example of a Constructor:🎯

💻 code
class Car {
public:
    Car() { // Constructor
        cout << "Car created!" << endl;
    }
};

When you create a Car object, the constructor runs automatically.

3Why Use Destructors?💡

Destructors are called when an object is destroyed. They are useful for cleaning up resources, like memory or file handles. Just like constructors, if you don’t define one, C++ provides a default destructor.

4Example of a Destructor:🚀

💻 code
class Car {
public:
    ~Car() { // Destructor
        cout << "Car destroyed!" << endl;
    }
};

When the Car object goes out of scope, the destructor runs automatically.

5Creating a Class with Constructor and Destructor🔍

Let's put it all together! Here’s how to create a class with both a constructor and a destructor:

💻 code
class Car {
public:
    Car() {
        cout << "Car created!" << endl;
    }
    ~Car() {
        cout << "Car destroyed!" << endl;
    }
};
💻 code
int main() {
    Car myCar; // Constructor is called here
    return 0; // Destructor is called here
}

6Benefits of Using Constructors and Destructors⭐

  • ✓ Control object initialization
  • ✓ Ensure resources are released
  • ✓ Improve code readability
  • ✓ Help manage complex resources like dynamic memory

7Practice Exercise🧩

Create a class called "Book" with a constructor that initializes the title and author. Add a destructor that outputs a message when a Book object is destroyed. Test it in a main function!

🎯 Practice Challenges

Master Constructors & Destructors by completing all 3 difficulty levels

🟢 EASY

Constructors & Destructors - Easy Challenge

Start with the basics. Perfect for beginners!

🟡 MEDIUM

Constructors & Destructors - Medium Challenge

Get more challenging. Build your confidence!

🔴 HARD

Constructors & Destructors - Hard Challenge

Master this concept. Prove your skills!

🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →

Ready to Master Constructors & Destructors? 🚀

Complete the challenges, take the quiz and keep your learning streak going!