Skillversitas

Other Operators in C++

In addition to arithmetic, relational, logical, and bitwise operators, C++ has several other operators that are important to understand. These operators include sizeof, the conditional (ternary) operator, the comma operator, scope resolution, member access, pointer, and casting operators. Each operator has a specific role that is frequently used in everyday C++ programming.

Understanding these operators will help programmers write more efficient and structured code. Some of them, such as sizeof and the ternary operator, are used very frequently, while others, such as casting operators, require a deep understanding of the C++ type system.

Operator Summary

Operator Name Description
sizeof Sizeof Returns the size of a data type in bytes
?: Ternary A short conditional operator
, Comma Evaluates multiple expressions
:: Scope Resolution Accesses members within a specific scope
. Dot Operator Accesses members of an object
-> Arrow Operator Accesses members through a pointer to an object
* Dereference Accesses the value a pointer points to
& Address-of Gets the memory address of a variable
static_cast Static Cast Static type conversion
dynamic_cast Dynamic Cast Dynamic type conversion (runtime)
const_cast Const Cast Adds/removes const
reinterpret_cast Reinterpret Cast Raw type conversion

Code Example

#include <iostream>
#include <string>
using namespace std;

class Student {
public:
    string name;
    int age;

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // sizeof operator
    cout << "=== Operator sizeof ===" << endl;
    cout << "sizeof(char)   = " << sizeof(char) << " byte" << endl;
    cout << "sizeof(int)    = " << sizeof(int) << " bytes" << endl;
    cout << "sizeof(float)  = " << sizeof(float) << " bytes" << endl;
    cout << "sizeof(double) = " << sizeof(double) << " bytes" << endl;
    cout << "sizeof(bool)   = " << sizeof(bool) << " bytes" << endl;

    int arr[] = {10, 20, 30, 40, 50};
    cout << "sizeof(arr)    = " << sizeof(arr) << " bytes" << endl;
    cout << "Number of elements  = " << sizeof(arr) / sizeof(arr[0]) << endl;

    // Ternary operator (?:)
    cout << "\n=== Operator Ternary (?:) ===" << endl;
    int a = 15, b = 23;
    int max = (a > b) ? a : b;
    cout << "Largest value of " << a << " and " << b << " = " << max << endl;

    string status = (a % 2 == 0) ? "Even" : "Odd";
    cout << a << " is an " << status << " number" << endl;

    // Nested ternary
    int score = 85;
    string grade = (score >= 90) ? "A" :
                   (score >= 80) ? "B" :
                   (score >= 70) ? "C" :
                   (score >= 60) ? "D" : "F";
    cout << "Score " << score << " = Grade " << grade << endl;

    // Comma operator
    cout << "\n=== Comma Operator ===" << endl;
    int x, y;
    x = 10, y = 20;
    cout << "x = " << x << ", y = " << y << endl;

    int result = (x = 30, y = 40, x + y);
    cout << "result = " << result << endl;

    // Ternary for operations inside a loop
    cout << "\n=== Ternary in a Loop ===" << endl;
    for (int i = 1; i <= 10; i++) {
        cout << i << " = " << ((i % 2 == 0) ? "Even" : "Odd") << endl;
    }

    // Pointer operators
    cout << "\n=== Pointer Operators ===" << endl;
    int val = 42;
    int *ptr = &val;

    cout << "value of val   = " << val << endl;
    cout << "address of val = " << &val << endl;
    cout << "value of ptr   = " << ptr << endl;
    cout << "value of *ptr  = " << *ptr << endl;

    // Arrow operator
    cout << "\n=== Dot & Arrow Operator ===" << endl;
    Student student1;
    student1.name = "John";
    student1.age = 20;
    student1.display();

    Student student2;
    student2.name = "Alice";
    student2.age = 21;

    Student *ptrStudent = &student2;
    ptrStudent->display();

    // Casting operators
    cout << "\n=== Casting Operators ===" << endl;

    // static_cast
    int intVal = 7;
    double dblVal = static_cast<double>(intVal) / 2;
    cout << "static_cast<int>(7) / 2 = " << dblVal << endl;

    // const_cast
    const int constVal = 10;
    int &nonConstRef = const_cast<int&>(constVal);
    cout << "const_cast: " << constVal << " -> " << nonConstRef << endl;

    // reinterpret_cast
    int intNum = 65;
    char *charPtr = reinterpret_cast<char*>(&intNum);
    cout << "reinterpret_cast: " << intNum << " -> '" << *charPtr << "'" << endl;

    return 0;
}

Code Explanation

  • sizeof: A compile-time operator that returns the size of a data type in bytes. Very useful for counting the number of elements in an array with sizeof(arr) / sizeof(arr[0]).
  • Ternary ?:: A short form of if-else. Format: condition ? valueIfTrue : valueIfFalse. It can be nested for multiple conditions.
  • Comma ,: Evaluates expressions from left to right and returns the value of the last expression. Often used in for loops.
  • Dot .: Accesses members of an object directly.
  • Arrow ->: Accesses members through a pointer to an object. The same as (*ptr).member.
  • static_cast: The most common and safe type conversion. It is performed at compile time. Suitable for numeric conversions and upcasting.
  • dynamic_cast: A type conversion performed at runtime on polymorphic classes. Returns nullptr if the conversion fails (for pointers).
  • const_cast: Adds or removes the const qualifier from a variable.
  • reinterpret_cast: A raw type conversion without checking type compatibility. Very dangerous if used carelessly.

Everyday Use Cases

#include <iostream>
#include <vector>
using namespace std;

class Product {
public:
    string name;
    double price;

    Product(string n, double h) : name(n), price(h) {}
};

double calculateDiscount(double price, bool isMember) {
    return isMember ? price * 0.9 : price;
}

int main() {
    // Calculate the discount with the ternary operator
    cout << "=== Online Store ===" << endl;
    double price = 150000;
    bool isMember = true;

    double finalPrice = calculateDiscount(price, isMember);
    cout << "Original price  : $" << price << endl;
    cout << "Member?         : " << (isMember ? "Yes" : "No") << endl;
    cout << "Final price     : $" << finalPrice << endl;

    // Use sizeof to iterate over an array
    cout << "\n=== Product Data ===" << endl;
    double productPrice[] = {25000, 50000, 75000, 100000};
    int itemCount = sizeof(productPrice) / sizeof(productPrice[0]);

    double totalSpent = 0;
    for (int i = 0; i < itemCount; i++) {
        cout << "Item " << (i + 1) << ": $" << productPrice[i] << endl;
        totalSpent += productPrice[i];
    }
    cout << "Total: $" << totalSpent << endl;

    // Use pointers with dynamic_cast
    cout << "\n=== Polymorphism ===" << endl;
    vector<Product*> list;
    list.push_back(new Product("Laptop", 8500000));
    list.push_back(new Product("Mouse", 150000));

    for (Product* p : list) {
        cout << p->name << ": $" << p->price << endl;
    }

    // Cleanup
    for (Product* p : list) {
        delete p;
    }

    return 0;
}

Conclusion

Other operators in C++ include sizeof for data sizes, ?: for short conditions, , for multiple expressions, :: for scope resolution, . and -> for member access, and four kinds of casting operators. Choosing the right casting operator is very important: use static_cast for general conversions, dynamic_cast for polymorphism, const_cast for modifying const, and reinterpret_cast only for low-level operations.