Szerkesztő:LinguisticMystic/cpp/ConstructorsDestructors
🔧 Constructors and Destructors in C++
[szerkesztés]In C++, constructors and destructors are special member functions that help manage an object’s lifecycle—from creation to destruction. Understanding these tools is fundamental to object-oriented programming and memory/resource management in C++.
🔹 What is a Constructor?
[szerkesztés]A constructor is automatically called when an object of a class is created. It is mainly used to:
- Initialize member variables.
- Allocate memory or resources (e.g., open files or connections).
- Ensure the object is in a valid state from the moment it exists.
Key rules:
[szerkesztés]- A constructor has no return type, not even
void. - It must have the same name as the class.
- It is typically placed in the public section of the class.
✅ Example 1: Uniform Initialization (No Constructor)
[szerkesztés]#include <iostream>
class Dog {
public:
std::string name;
int age;
int weight;
void print() {
std::cout << "My name is " << name;
std::cout << ", I'm " << age;
std::cout << " years old and my weight: " << weight << " kg\n";
}
};
int main() {
Dog bars {"Barsic", 11, 25}; // Direct public member initialization
bars.print();
}
📌 Explanation: This only works because all members are public. It’s simple but not encapsulated.
🔒 Why Not Use Public Members?
[szerkesztés]Public data members:
- Break encapsulation (one of the pillars of OOP).
- Make your code fragile and harder to maintain.
- Allow uncontrolled external modifications.
If you make data private, you can no longer initialize like Dog bars {"Barsic", 11, 25}. You need a constructor.
🛠️ Example 2: Using a Constructor for Private Data
[szerkesztés]#include <iostream>
class Dog {
private:
std::string m_name;
int m_age;
int m_weight;
public:
Dog() {
m_name = "Barsic";
m_age = 11;
m_weight = 25;
}
void print() {
std::cout << "My name is " << m_name;
std::cout << ", I'm " << m_age;
std::cout << " years old and my weight: " << m_weight << " kg\n";
}
};
int main() {
Dog bars; // Constructor is called automatically
bars.print();
}
📝 Explanation:
- Constructor sets default values.
- When
Dog bars;is created, the constructor runs immediately. - If you add
std::cout << "Constructor called!\n";to the constructor, you’ll see it in the output.
🔄 Types of Constructors
[szerkesztés]C++ supports three main types of constructors:
1. 🧱 Default Constructor
[szerkesztés]A constructor that takes no arguments.
class Car {
public:
Car() {
std::cout << "Car created!\n";
}
};
2. 🔧 Parameterized Constructor
[szerkesztés]A constructor that takes arguments to initialize the object.
class Car {
private:
std::string m_brand;
public:
Car(std::string brand) {
m_brand = brand;
std::cout << "Car " << m_brand << " created!\n";
}
};
Usage:
Car bmw("BMW"); // Car BMW created!
3. 📋 Copy Constructor
[szerkesztés]Creates a new object as a copy of an existing object.
class Car {
private:
std::string m_brand;
public:
Car(const Car &obj) { // Must use const reference
m_brand = obj.m_brand;
std::cout << "Car " << m_brand << " copied!\n";
}
};
Usage:
Car original("Audi");
Car copy(original); // Car Audi copied!
🔁 Multiple Constructors (Constructor Overloading)
[szerkesztés]You can define multiple constructors as long as their parameter lists are different.
class Car {
public:
Car() {
std::cout << "Car created!\n";
}
Car(std::string brand) {
std::cout << "Car " << brand << " created!\n";
}
Car(const Car& obj) {
std::cout << "Car copied!\n";
}
};
🧼 Destructor
[szerkesztés]A destructor is a special member function that is automatically called when:
- The object goes out of scope, or
- The object is deleted with
delete.
Syntax:
[szerkesztés]~ClassName() {
// cleanup code
}
🔑 Rules:
- No parameters.
- No return type.
- Only one destructor per class.
🧪 Example:
[szerkesztés]class Car {
public:
Car() {
std::cout << "Car created!\n";
}
~Car() {
std::cout << "Car destroyed!\n";
}
};
int main() {
Car myCar;
std::cout << "Main function ending...\n";
return 0;
}
🖨️ Output:
Car created! Main function ending... Car destroyed!
💡 The destructor is always called last, after main() ends or after an object goes out of scope.
🔄 When Destructors Are Called
[szerkesztés]| Situation | Destructor Called? |
|---|---|
| Object goes out of scope | ✅ Yes |
delete is used on object pointer |
✅ Yes |
| Object is statically allocated | ✅ Yes |
| Object is dynamically allocated | ❌ No (unless you call delete) |
💡 When Are Constructors/Destructors Useful?
[szerkesztés]- Constructor: Set up an object, allocate memory, open resources (file handles, sockets).
- Destructor: Clean up memory, close files, release handles or connections.
🔚 Conclusion
[szerkesztés]- Constructors and destructors are fundamental to C++ class design.
- Constructors ensure that objects are initialized properly.
- Destructors help in cleaning up resources when objects are no longer needed.
- Use default, parameterized, and copy constructors as appropriate.
- Always define a destructor if your class handles resources (e.g., memory, files).