Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

C++ Core Syntax: Default Arguments, Overloading, Const Semantics, and Dynamic Memory

Tech May 9 4

Default Arguments

Default parameter values must be assigned from right to left.

int add(int x = 10, int y);     // error
int add(int x, int y = 20);     // ok
int add(int x = 10, int y = 20); // ok

A default may be given in either the function declaration or its definition, but not both within the same scope; the initializer must appear exactly once. Using defaults can reduce the work done at the call site because fewer arguments are pushed explicitly.

Inline Functions

Declaring a function inline asks the compiler to expand the function body directly at the point of invocation, eliminating the cost of parameter pushing, stack-frame creation, and teardown. The request is not binding: recursive functions or those with large bodeis are often emitted as ordinary callable routines. When inlining succeeds, no separate linker symbol is generated for the routine.

Debug builds generally ignore inline so that developers can set breakpoints inside the function; the optimization is effective in release builds tuned for speed.

Function Overloading

Functions that share an identifier but differ in parameter count or parameter types form an overload set. Every candidate must be declared in the same scope. A top-level const or volatile qualifier on a by-value parameter does not produce a distinct overload, but const or volatile attached to a pointer or reference type does change the signature. Two functions whose parameter lists are identical and whose return types differ are not overloads.

C++ implements overloading through name mengling: the generated object symbol incorporates the function name plus encoded parameter types. C compilers use only the function name, which is why overloading is unavailable in C. To expose C++ functions to C, wrap the declarations in extern "C"; when C++ code includes C headers, place the C declarations inside extern "C" guards, commonly conditioned on the predefined __cplusplus macro.

The const Qualifier

A const variable in C++ is a named constant that must be initialized; once defined, it cannot act as the target of an assignment.

const int cap = 50;
cap = 100;  // error: assignment of read-only variable

Two frequent errors are:

  • Assigning direclty to a constant object.
  • Letting a non-const pointer or reference capture the address of a constant, which opens a path to indirect modification.

Compared with C, where a const object may be left uninitialized and is merely a read-only variable, C++ requires initialization. If the initializer is not a constant expression, the resulting object is a read-only variable rather than a true compile-time constant:

int a = 20;
const int b = a;  // read-only variable, not a compile-time constant in this context

The compilation strategy also differs. C generates memory accesses for const objects as if they were variables, whereas C++ substitutes the initializer value at every use site when the object is a true constant.

const with Pointers

The qualifier binds to the nearest type to its left, or to the base type if it is leftmost.

const float* p;        // pointer to constant float
float const* p;        // equivalent
float* const p = &f;   // constant pointer to mutable float
const float* const p;  // constant pointer to constant float

In the first two forms, the pointee cannot be modified through the pointer. In the third, the pointer’s address is fixed while the data may change. The fourth fixes both.

Pointer conversion rules involving const follow these patterns:

int*        <= const int*   // invalid: discards const qualifier
const int*  <= int*         // valid: adds const qualifier
int**       <= const int**  // invalid: unsafe conversion
const int** <= int**        // invalid
int**       <= int* const*  // invalid
int* const* <= int**        // valid: adds const at the intermediate level

If no asterisk appears to the right of const, the qualifier does not create a distinct pointer category.

References

A reference is an alias for an existing object, offering safer semantics than a raw pointer. It must be initialized when created, cannot be null, and supports only a single level of indirection. At the assembly level, references compile to the same machine instructions as pointers.

An lvalue reference binds to a named object with stable storage:

int score = 90;
int& alias = score;

An rvalue reference (&&), available since C++11, binds to temporaries:

int&& temp = 30;  // extends the temporary's lifetime

All temporaries are rvalues. Although an rvalue reference variable itself is an lvalue—and can therefore be captured by an lvalue reference—it cannot directly bind to an existing named lvalue.

Dynamic Allocation with new and delete

new and delete are language operators, distinct from the C library routines malloc and free. new both allocates storage and initializes the object. When allocation fails, new throws a std::bad_alloc exception; the std::nothrow variant returns a null pointer instead. malloc indicates failure by returning nullptr.

double* q1 = new double(2.718);
double* q2 = new (std::nothrow) double;
const double* q3 = new const double(1.414);

// placement new
int slot = 0;
int* q4 = new (&slot) int(77);

C++ allows implicit conversions among many built-in types, so the language is not strictly type-safe.

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.