Lesson 6 +30 XP

Operators in C++

Operators in C++

C++ keeps every C operator (arithmetic, relational, logical, bitwise, assignment, conditional and so on) and adds new ones. The additions are the most examinable: the scope resolution operator ::, the memory operators new and delete, the member-pointer operators, the insertion and extraction operators and the manipulators endl and setw.

1. Operators Inherited from C

  • Arithmetic: + - * / %
  • Relational: < <= > >= == !=
  • Logical: && || !
  • Bitwise: & | ^ ~ << >>
  • Assignment: = += -= *= /= %= and the bitwise forms
  • Increment / decrement: ++ - (prefix and postfix)
  • Conditional: ? :
  • Others: sizeof , & (address) * (indirection) . ->

2. New Operators in C++

OperatorName
<<insertion (put-to) operator
>>extraction (get-from) operator
::scope resolution operator
::*pointer-to-member declarator
->*pointer-to-member operator (through a pointer to the object)
.*pointer-to-member operator (through the object)
newmemory allocation operator
deletememory release operator
endlline feed manipulator
setwfield width manipulator
typeid, the four _cast operatorstype information and conversions (Lesson 21)

<< and >> are C's shift operators, overloaded by the stream library for input and output. Which meaning applies depends on the operands: cout << x outputs, a << 2 shifts.

3. Scope Resolution Operator ::

C++ is block-structured: a variable declared in an inner block hides a variable of the same name in an outer block. In C there is no way to reach the hidden global variable. In C++ the unary :: refers to the global version.

texttt{::} variable-name
C++
#include <iostream>
using namespace std;

int m = 10; // global m

int main() {
    int m = 20; // local m hides the global m
    {
        int k = m;  // k = 20 (local m)
        int m = 30; // a third m, in the inner block
        cout << "inner block:" << endl;
        cout << "  k   = " << k << endl;
        cout << "  m   = " << m << endl;
        cout << "  ::m = " << ::m << endl; // global m
    }
    cout << "outer block:" << endl;
    cout << "  m   = " << m << endl;
    cout << "  ::m = " << ::m << endl;
    return 0;
}

Output:

OUTPUT
inner block:
  k   = 20
  m   = 30
  ::m = 10
outer block:
  m   = 20
  ::m = 10

:: cannot reach the m of an intermediate block; it always means the global one.

The binary form class-name::member has two other major uses:

  1. Defining member functions outside the class: void Student::show() { ... } (Lesson 13).
  2. Accessing static members and names inside a namespace: Student::count, std::cout.

4. Memory Management Operators new and delete

C uses the library functions malloc() and free(). C++ provides two operators that do the same job more safely and easily. Memory taken this way comes from the free store (heap) and stays allocated until it is released, so its lifetime is controlled by the programmer.

FormMeaning
p = new type;allocate one object
p = new type(value);allocate and initialise
p = new type[size];allocate an array
delete p;release one object
delete [] p;release an array
C++
#include <iostream>
using namespace std;

int main() {
    int* p = new int; // one int
    *p = 25;
    float* q = new float(7.5); // allocate and initialise

    int n = 4;
    int* arr = new int[n]; // array whose size is known only at run time
    for (int i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
    }

    cout << "*p = " << *p << ", *q = " << *q << endl;
    cout << "array:";
    for (int i = 0; i < n; i++) {
        cout << " " << arr[i];
    }
    cout << endl;

    delete p; // release single objects
    delete q;
    delete[] arr; // release the array with delete []
    return 0;
}

Output:

OUTPUT
*p = 25, *q = 7.5
array: 10 20 30 40

Why new is better than malloc()

new / deletemalloc() / free()
operators (part of the language)library functions (<cstdlib>)
computes the size automatically: no sizeofneeds sizeof
returns the correct pointer type: no castreturns void*; C++ needs a cast
can initialise the object: new int(5)memory is uninitialised
calls the constructor (and delete calls the destructor)knows nothing about constructors
can be overloadedcannot
failure throws bad_alloc (old compilers returned 0)failure returns NULL

If memory runs out, standard new throws a std::bad_alloc exception; the form new (nothrow) int[n] returns NULL instead (Unit IV).

5. Manipulators endl and setw

Manipulators are operators used with << to format output. endl ends the line (like " ") and flushes the buffer. setw(n) (from <iomanip>) prints the next item in a field n characters wide, right-justified.

C++
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int basic = 950, allowance = 95, total = 1045;
    cout << setw(10) << "Basic" << setw(8) << basic << endl;
    cout << setw(10) << "Allowance" << setw(8) << allowance << endl;
    cout << setw(10) << "Total" << setw(8) << total << endl;
    return 0;
}

Output:

OUTPUT
     Basic     950
 Allowance      95
     Total    1045

Without setw, the numbers would not line up. More manipulators and user-defined manipulators are covered in Unit IV.

6. Pointer-to-Member Operators

C++ lets you take a pointer to a member of a class (not to a member of one particular object). ::* declares it, and .* or ->* uses it with an object or a pointer to an object.

C++
#include <iostream>
using namespace std;

class Box {
public:
    int width;
    int area(int h) {
        return width * h;
    }
};

int main() {
    int Box::*pw = &Box::width;       // pointer to data member
    int (Box::*pf)(int) = &Box::area; // pointer to member function

    Box b;
    Box* pb = &b;
    b.*pw = 6;                             // .* with an object
    cout << "width = " << pb->*pw << endl; // ->* with a pointer
    cout << "area  = " << (b.*pf)(4) << endl;
    return 0;
}

Output:

OUTPUT
width = 6
area  = 24
💡 Tip

Key points to remember

  • New operators: << >> :: ::* ->* .* new delete endl setw.
  • Unary :: reaches a global variable hidden by a local one; binary :: defines members outside a class and names static and namespace members.
  • new computes the size, returns the right type, can initialise and calls constructors; release with delete (or delete [] for arrays).
  • endl = newline + flush; setw(n) right-justifies the next item in n columns.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain the scope resolution operator with a program. (5 Marks)
  • Write: the hiding problem, the unary form with the three-level m program and its output, and the binary uses.
  • Q2. Explain new and delete operators. What are their advantages over malloc() and free()? (5 Marks)
  • Write: the forms table, the program, and the comparison table (at least five rows).
  • Q3. List the new operators introduced in C++. (2.5 Marks)
  • Q4. What are manipulators? Explain endl and setw with an example. (2.5 Marks)
  • Write: the definition and the aligned salary table program.