new & delete
new expression heap par memory allocate karta hai AUR agar type ek class hai, uska constructor bhi call karta hai — malloc() sirf raw bytes deta hai, koi initialization nahi. delete memory free karta hai AUR destructor bhi call karta hai.
Array allocate karne ke liye new[] aur delete[] use hota hai (alag syntax) — single object ke new/delete se mix mat karo, warna undefined behavior hai.
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {
cout << "Constructor called" << endl;
}
~Point() {
cout << "Destructor called" << endl;
}
};
int main() {
Point *p = new Point(3, 4); // constructor auto-chalta hai
cout << p->x << endl;
delete p; // destructor auto-chalta hai
int *arr = new int[5]; // array allocation
delete[] arr; // array deallocation — [] zaroori
return 0;
}- new = malloc() + constructor call
- delete = free() + destructor call
- Array ke liye new[]/delete[] — mismatch undefined behavior hai
"Placement new" ek existing memory location par object construct karta hai (naya memory allocate kiye bina) — advanced technique, usually custom memory allocators ya performance-critical code mein use hoti hai. Beginners ko usually iski zaroorat nahi padti.
#include <new>
char buffer[sizeof(Point)];
Point *p = new (buffer) Point(1, 2); // buffer mein hi construct hua, naya alloc nahi
p->~Point(); // manually destructor call karna padta hai — delete use nahi hotaC++11 se nullptr introduce hua — type-safe null pointer constant. NULL (C se inherited) actually 0 ka macro hai, jo kabhi-kabhi ambiguity create kar sakta hai (integer 0 se confuse ho sakta hai overloaded functions mein). nullptr modern C++ mein hamesha prefer kiya jaata hai.
int *p1 = NULL; // purana style, kaam karta hai
int *p2 = nullptr; // modern, type-safe — preferred
void func(int x) { cout << "int version" << endl; }
void func(int *p) { cout << "pointer version" << endl; }
func(NULL); // ambiguous ho sakta hai (kuch compilers mein)!
func(nullptr); // hamesha pointer version — clear