←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

C++ Operators: Scope Resolution, 'new' & 'delete' Memory Management

Study material and explanations for Unit 1

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:

  1. Scope Resolution Operator (::)
  2. Dynamic Memory Operators (new and delete)

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).

Four Key Roles of the Scope Resolution Operator (::)
1. Access Global Variables
Accesses a global variable when a local variable has the same name (::count).
2. Define Functions Outside Class
Tells C++ which class a member function belongs to (void Student::display()).
3. Access Static Class Members
Calls static variables or functions without creating an object (Math::pi).
4. Namespace Resolution
Tells the compiler which library namespace to use (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:

  1. new operator: Allocates memory from the heap while the program is running.
  2. delete operator: 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 use delete[] 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 to n spaces. 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:

  1. 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 count and ::count.
    • Mention its other use: defining member functions outside the class declaration.
  2. Differentiate between the new operator and malloc() function.
    Model Answer:
    • Draw a 2-column table comparing new (operator, calls constructors, type-safe) vs. malloc() (function, does not call constructors, returns void*).

Frequently Asked 10-Mark Questions:

  1. Explain dynamic memory management in C++ using new and delete operators. 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 new and forget to call delete, that memory stays reserved and cannot be reused, eventually slowing down or crashing the computer.