Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

C++ Reference, Const Qualifier, Memory Management, and Function Features

Tech Oct 9 17

1 Reference Concepts

1.0 Fundamentals
  • References must be initialized to a varible upon declaration.
  • References can only bind to variables, not expressions or constants.
1.1 Variable References
int a = 0;
int& ref = a; // ref is of type int&
  • ref becomes an alias for a; operations on ref directly affect a.
1.2 Returning References from Functions
#include <iostream>
int global = 4;
int& modifyGlobal() { return global; }

int main() {
    modifyGlobal() = 40; // Modifies the returned reference
    std::cout << global << std::endl; // Outputs 40
    return 0;
}
  • Returning a reference to a local variable is prohibited since local variables are destroyed after function execution.
1.3 Constant References

Prevent modification through the reference:

#include <iostream>
int main() {
    int val = 100;
    const int& cref = val;
    val = 1000;     // Allowed
    // cref = 1000; // Compilation error: cref is read-only
    return 0;
}
1.4 Conversion Between Reference Types
  1. const T& and T& are distinct types.
  2. A const reference can be initialized by a non-const reference or variable.
  3. Constants and const references cannot initialize non-const references.
1.5 Const Qualifier Usage
const int* ptr = &n; // Pointer to constant integer
const int& r = n;    // Constant reference

Key points:

  • A constant reference does not prevent modification of the original variable through other means.
  • A pointer to const cannot modify the pointed value.
  • A constant pointer (e.g., int* const) cannot be reassigned after initialization.

2 Dynamic Memory Allocation

2.1 new and delete Operators
T* ptr = new T;      // Allocate single element
delete ptr;          // Deallocate

T* arr = new T[N];   // Allocate array
delete[] arr;        // Deallocate array
  • T is any type; ptr must be a pointer of type T*.
2.2 Pointer Usage Guidelines
char* cptr = new int;    // Error: type mismatch
// *cptr = 'a';          // Invalid assignment
delete cptr;

int* iarr = new int[25];
// iarr[30] = 100;       // Out-of-bounds access
delete iarr;             // Should use delete[] for arrays

char* str = new char[10];
str[0] = 'K';
delete[] str;            // Correct deallocation

3 Inline Functions, Overloading, and Default Arguments

3.1 Inline Functions
inline int maximum(int x, int y) {
    return (x > y) ? x : y;
}
  • The inline keyword suggests the compiler replace calls with the function body to reduce overhead.
3.2 Function Overloading

Features:

  • Same funcsion name.
  • Different parameter types or counts.

The compiler selects the appropriate function based on argument types and count.

Example:

double max(double d1, double d2) { /*...*/ }    // Overload 1
int max(int i1, int i2) { /*...*/ }             // Overload 2
int max(int i1, int i2, int i3) { /*...*/ }     // Overload 3

max(3.4, 2.5);  // Calls overload 1
max(2, 4);      // Calls overload 2
max(1, 2, 3);   // Calls overload 3
// max(3, 2.4); // Error: ambiguous call

Note: Return type alone cannot differentiate overloads.

3.3 Default Arguments
void example(int a, int b = 2, int c = 3) { /*...*/ }

example(10);       // Equivalent to example(10, 2, 3)
example(10, 8);    // Equivalent to example(10, 8, 3)
// example(10, , 8); // Invalid; only trailing arguments can be omitted
  • Default arguments enhance backward compatibility when extending functions.

Concept Clarification:

  • Overloading requires parameter differences, not just count.
  • Differing return types alone do not constitute overloading.
  • Arguments with defaults must be specified consecutively from right to left.
  • Inline functions aim to reduce call overhead.
Tags: C++

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.