C++ Operators: Scope Resolution, ‘new’ & ‘delete’ Memory Management
1. Overview of Operators in C++ (In Simple Words)
C++ has all the regular operators that you already learned in C language:
- Arithmetic:
+,-,*,/,% - Relational / Comparison:
<,>,<=,>=,==,!= - Logical:
&&(AND),||(OR),!(NOT) - Assignment:
=,+=,-=,*=
In addition to these, C++ adds special operators for Object-Oriented Programming and dynamic memory management. The two most important ones asked in exams are:
- Scope Resolution Operator (
::) - Dynamic Memory Operators (
newanddelete)
2. The Scope Resolution Operator (::)
Imagine you have two variables with the exact same name: one global (defined outside all functions) and one local (defined inside main()).
Normally, the local variable hides the global variable inside the function. If you just write count, C++ uses the local one.
So how do you tell C++: “No, give me the global variable!”?
You put two colons :: before the variable name (::count).
::count).void Student::display()).Math::pi).std::cout).Easy Code Example:
#include <iostream>
using namespace std;
int count = 100; // Global variable
int main() {
int count = 10; // Local variable (same name!)
cout << "Local count: " << count << endl; // Prints: 10
cout << "Global count: " << ::count << endl; // Prints: 100 (using ::)
return 0;
}
3. Dynamic Memory Management: new and delete
Normally, when you create a variable like int a = 10;, memory is allocated on the Stack automatically.
But what if you do not know in advance how many students will take admission? You need to allocate memory during runtime from the Heap memory.
In C, we used tricky functions like malloc() and free(). But C++ makes it very simple with two keywords:
newoperator: Allocates memory from the heap while the program is running.deleteoperator: Frees that memory so RAM is not wasted.
How to Use new and delete:
#include <iostream>
using namespace std;
int main() {
// 1. Allocating memory for a single integer
int *ptr = new int(25); // Allocates 1 integer with initial value 25
cout << "Value: " << *ptr << endl; // Prints 25
// Free the memory
delete ptr;
ptr = nullptr; // Good practice: avoid dangling pointer
// 2. Allocating memory for an Array of 5 integers
int *arr = new int[5]; // Allocates space for 5 integers
arr[0] = 10;
arr[1] = 20;
// Freeing an array (Notice the square brackets [])
delete[] arr;
return 0;
}
Important Note: When deleting a single variable, use
delete ptr;. When deleting an array, always usedelete[] arr;.
Comparison: new & delete (C++) vs. malloc() & free() (C)
| Feature | new and delete (C++) |
malloc() and free() (C) |
|---|---|---|
| What are they? | Built-in C++ operators | Standard C library functions |
| Calls Constructor? | Yes! Automatically calls constructors and destructors | No! Just allocates raw bytes without initializing objects |
| Type Safety | Returns the exact pointer type (e.g. int*) |
Returns void*, needs manual typecasting |
| Size Calculation | Compiler automatically calculates size | You must calculate size manually using sizeof() |
| Initialization | Can initialize values directly (new int(50);) |
Cannot initialize values while allocating |
4. C++ Manipulators (<iomanip>)
Manipulators are special formatting functions used with cout << to change how output looks on the screen (like setting columns or decimal points).
To use manipulators like setw(), always write #include <iomanip> at the top of your program.
Common Manipulators:
endl: Moves the cursor to the next line (same as\n) and clears the output buffer.setw(n): Sets the width of the output field tonspaces. Great for printing neat tables!setprecision(n): Controls how many digits appear after the decimal point in floating-point numbers.setfill(ch): Fills empty spaces with a custom character (like*or-).
#include <iostream>
#include <iomanip> // Must include this!
using namespace std;
int main() {
cout << setw(10) << "Subject" << setw(10) << "Marks" << endl;
cout << setw(10) << "C++" << setw(10) << 85 << endl;
cout << setw(10) << "Maths" << setw(10) << 92 << endl;
return 0;
}
5. Type Casting (Changing Data Types)
Type casting means converting a value from one data type to another (for example, converting a float with decimals into an int).
float marks = 85.75;
// Old C-Style syntax:
int x = (int)marks; // Result: 85
// C++ Functional syntax:
int y = int(marks); // Result: 85
// Modern C++ static_cast (Safest method):
int z = static_cast<int>(marks); // Result: 85
DAVV Exam Preparation Tips
Frequently Asked 5-Mark Questions:
- Explain the purpose and usage of the Scope Resolution Operator (
::) with an example.
Model Answer:- Explain that
::is used to access a global variable when a local variable has the same name. - Write a short 8-line code example showing both
countand::count. - Mention its other use: defining member functions outside the class declaration.
- Explain that
- Differentiate between the
newoperator andmalloc()function.
Model Answer:- Draw a 2-column table comparing
new(operator, calls constructors, type-safe) vs.malloc()(function, does not call constructors, returnsvoid*).
- Draw a 2-column table comparing
Frequently Asked 10-Mark Questions:
- Explain dynamic memory management in C++ using
newanddeleteoperators. How do you allocate and free single variables and arrays? What is a memory leak?
Model Answer:- Explain dynamic allocation: allocating memory from Heap at runtime when the size is not known in advance.
- Show syntax and code for single variables (
new int(10); delete ptr;) and arrays (new int[n]; delete[] arr;). - Highlight the bracket syntax
delete[]for arrays. - Explain Memory Leak: if you allocate heap memory using
newand forget to calldelete, that memory stays reserved and cannot be reused, eventually slowing down or crashing the computer.