📚 C++ Constructors Deep Dive [Playlist Link]
🏗️ What is a Constructor?
A constructor is a special method that automatically runs when an object is instantiated. It initializes memory and sets default values for class members.
Example from Video (0:00)
Without a constructor, uninitialized variables contain garbage values:
class Entity {
public:
float X, Y;
void Print() { cout << X << ", " << Y; }
};
int main() {
Entity e;
e.Print(); // Output: random values like -4.316e+08, 4.562e-41
}
Solution: Use a constructor to initialize X and Y to 0:
class Entity {
public:
float X, Y;
Entity() { // Default constructor
X = 0;
Y = 0;
}
};
Now, e.Print() outputs 0, 0.
🔄 Default Constructor
If you don’t define a constructor, C++ provides a default constructor that does nothing (doesn’t initialize members).
Key Behavior (2:48)
- Primitive types (e.g.,
int,float) are not auto-initialized in C++. - Example error when accessing uninitialized members:
Entity e; cout << e.X; // Error: "uninitialized local variable 'e' used"
🎯 Parameterized Constructors
Constructors can be overloaded to accept parameters for custom initialization.
Example (4:21)
class Entity {
public:
float X, Y;
Entity(float x, float y) {
X = x;
Y = y;
}
};
int main() {
Entity e(10.0f, 5.0f); // Initialize with X=10, Y=5
e.Print(); // Output: 10, 5
}
🚫 Restricting Object Creation
1. Private Constructor (5:35)
Use a private constructor to prevent instantiation (e.g., for utility classes with only static methods):
class Logger {
private:
Logger() {} // Can't create Logger objects
public:
static void Log(const char* message) { /* ... */ }
};
// Logger l; // Error: constructor is private
2. Delete Default Constructor (6:18)
Explicitly delete the default constructor:
class Logger {
public:
Logger() = delete; // No default constructor
static void Log(const char* message) { /* ... */ }
};
📝 Key Takeaways
- Always initialize variables in constructors to avoid garbage values.
- Overload constructors for flexibility in object creation.
- Use private constructors or
= deleteto restrict object instantiation.
🔗 Video Reference Links
- Introduction to Constructors (0:00)
- Parameterized Constructors (4:21)
- Private Constructors (5:35)
- Deleted Constructors (6:18)
With these notes, you’ve covered all key points from the video! 🚀 Revisit the links above if you need a quick refresher.
