Programming Languages · Programming in C++
C++ Basics References and Functions
Overview
C++ provides several ways to pass arguments to functions and to make functions efficient and expressive.
This lesson covers reference variables, the three parameter-passing mechanisms (by value, by pointer, by reference), default arguments, inline functions, function overloading, return by reference, and the scope resolution operator.
These features are heavily tested in UGC NET through code-tracing and statement-based questions because they depend on precise rules, not memorisation.
Before studying this lesson, you should know basic C++ syntax, data types, variables, pointers, and how a function is declared and defined.
Key concepts
- Reference variable: An alias for an existing object. Declared as
int &r = x;. Must be initialised at declaration; cannot be made to refer to another object later; no null reference. - Pass by value: The formal parameter is a copy of the actual argument. Changes inside the function do not affect the caller's variable.
- Pass by pointer: The formal parameter is a pointer holding the address of the actual argument. The function can modify the caller's variable using
*p, provided the pointer is valid. - Pass by reference: The formal parameter is an alias of the actual argument. Changes inside the function directly modify the caller's variable.
- const reference parameter:
const T &binds to the argument without copying and forbids modification through the reference. Preferred for large objects. - Default argument: A value supplied in the function declaration that is used when the caller omits that argument.
Defaults must be trailing (rightmost) parameters; once a parameter has a default, all parameters to its right must also have defaults. - Inline function: A function declared with the
inlinekeyword. It suggests to the compiler that the function body be substituted at each call site to avoid call overhead. The compiler may ignore the suggestion.
Typically defined in a header; multiple identical definitions across translation units are allowed under the One Definition Rule (ODR). - Function overloading: Multiple functions with the same name but different parameter lists (different number, types, or order of parameters). Return type alone cannot distinguish overloads.
The compiler resolves the call at compile time (static polymorphism). - Function signature: In C++, the signature for overloading is the function name plus the parameter types (and for member functions, const/ref qualifiers). Return type is not part of the signature.
- Return by reference: A function returns an alias (lvalue) to an object. Safe only if the referred object outlives the function call (e.g., static local, global, or a parameter passed by reference).
Returning a reference to a local automatic variable is undefined behaviour. - Scope resolution operator
::: Used to qualify a name.::xrefers to the globalxwhen a localxshadows it;Class::memberdefines or accesses a class member outside the class. - Array parameter decay: A parameter declared as
int a[]orint a[10]is adjusted toint *a. Thereforesizeof(a)inside the function gives the pointer size, not the array size.
How it works
- Function declaration and definition: A declaration (prototype) tells the compiler the function's name, return type, and parameter types. A definition provides the body.
Default arguments are normally specified in the declaration, not repeated in the definition. - Parameter binding at call time:
- By value: the argument expression is evaluated and its value is copied into the parameter. The parameter is a distinct object.
- By pointer: the argument must be an address (or a pointer). The pointer parameter is a copy of that address; dereferencing it accesses the caller's object.
- By reference: the parameter is bound directly to the argument object; no copy is made. The argument must be an lvalue (something with an address) unless the reference is
const.
- Modification semantics:
- Value parameter: modifying the parameter changes only the local copy.
- Pointer parameter:
*p = valuemodifies the caller's object;p = otherchanges only the local pointer. - Reference parameter: any assignment to the parameter modifies the caller's object.
- Default arguments: At the call site, omitted trailing arguments are filled with defaults. You cannot omit an earlier argument while supplying a later one. Default expressions are evaluated at the call site.
A default argument cannot be redefined in the same scope. - Inline expansion: The compiler may replace a call with the function body. This eliminates call/return overhead but can increase code size.
Recursive functions, functions with loops, or functions whose address is taken are often not inlined.inlineis a request, not a command. - Overload resolution: The compiler collects functions with the same name, forms candidate sets, and chooses the best match based on exact match, promotions, and conversions. Ambiguity arises when two overloads are equally good.
Overloading is resolved at compile time; virtual functions (runtime polymorphism) are a different topic. - Return by reference: The function's return type is
T&. The returned expression must be an lvalue that remains valid after the function returns. It can be used on the left side of an assignment, enabling expressions likepick(a,b) = 100;. - Scope resolution: Inside a function, a local variable can hide a global variable. Use
::nameto access the global. For class members,ClassName::memberaccesses the class scope.
Drawing the diagram…
Worked examples
Example 1 (pass by value and reference)
#include <iostream>
using namespace std;
void change(int a, int &b) {
a = a + 10;
b = b + 10;
}
int main() {
int x = 5, y = 7;
change(x, y);
cout << x << " " << y;
return 0;
}
Trace: x is passed by value to a, so a becomes 15 but x remains 5. y is passed by reference to b, so b = 7 + 10 = 17 changes y to 17. Output: 5 17.
Example 2 (default arguments and overloading)
#include <iostream>
using namespace std;
int area(int s, int t = 2) { return s * t; }
int main() {
cout << area(3) << " " << area(3, 4);
return 0;
}
area(3) uses default t = 2, returns 3×2 = 6. area(3,4) returns 3×4 = 12. Output: 6 12. Note: if a function is declared as int f(int a, int b = 4, int c = 5);, valid calls are f(1), f(1,2), and f(1,2,3). You cannot call f(1, , 3).
Example 3 (reference aliasing)
#include <iostream>
using namespace std;
int main() {
int x = 10;
int &r = x;
r = 20;
int y = r;
y = 30;
cout << x << " " << r << " " << y;
return 0;
}
r is an alias of x. r = 20 makes x = 20. y = r copies 20 into y. y = 30 changes only y. Output: 20 20 30.
Example 4 (pointer parameter and common trap)
The correct pointer-based swap is:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
Call with swap(&p, &q);. A common mistake is declaring int *temp; and writing temp = a; a = b; b = temp;—this swaps the pointer values, not the pointed-to integers, and does not modify the caller's variables. The temporary must be int and the values must be accessed through *a and *b.
Example 5 (return by reference and dangling reference)
#include <iostream>
using namespace std;
int& bad() {
int local = 5;
return local; // undefined behaviour
}
int& good(int &x) {
return x;
}
int main() {
int a = 3;
good(a) = 9;
cout << a;
return 0;
}
good(a) returns a reference to a, so good(a) = 9 assigns 9 to a. Output: 9. The function bad() returns a reference to a local variable whose lifetime ends when bad() returns; using that reference is undefined behaviour. This is a standard UGC NET assertion-reason trap.
Comparison
| Feature | Pass by value | Pass by pointer | Pass by reference |
|---|---|---|---|
| Formal parameter | Copy of argument | Pointer holding address | Alias of argument |
| Can modify caller? | No | Yes, via *p | Yes |
| Null allowed? | Not applicable | Yes | No (must bind to object) |
| Rebindable? | Not applicable | Yes (pointer can point elsewhere) | No |
| Syntax at call | f(x) | f(&x) | f(x) |
| Common use | Small data, no side effects | C-style arrays, optional arguments | Large objects, output parameters |
| Concept | Key rule | Trap |
|---|---|---|
| Default arguments | Must be trailing; specified in declaration | Cannot skip middle arguments |
| Function overloading | Different parameter list; return type ignored | Two functions differing only in return type are illegal |
| Inline function | Suggestion to compiler; not mandatory | Compiler may ignore; recursive functions often not inlined |
| Return by reference | Must return valid lvalue | Returning local automatic variable is undefined |
| Reference variable | Must be initialised; cannot be rebound | int &r; is illegal |
Revision summary
- A reference is an alias; it must be initialised and cannot be reseated.
- Pass by value copies; pass by reference aliases; pass by pointer copies an address.
- In a pointer swap, the temporary must be
int, notint *, and use*aand*b. - Default arguments are filled from right to left; you cannot skip a middle argument.
inlineis a request; the compiler may ignore it.- Overloading depends on parameter types, number, and order—not return type.
- Return by reference to a local variable is undefined; use static, global, or caller-owned objects.
::xaccesses the globalxwhen a localxshadows it.- Array parameters decay to pointers;
sizeofinside gives pointer size. const T&avoids copying and forbids modification.- The scope resolution operator also defines class member functions outside the class.
- Function overloading is compile-time polymorphism; virtual functions are runtime polymorphism.
Previous-year exam insights
- UGC NET often gives three swap implementations (value, reference, pointer) and asks which actually exchange caller values.
Check the parameter declaration and the use of*in the body. - Code-tracing questions test aliasing:
int &r = x; r = y;changesx, not the reference binding. - Default-argument questions ask how many arguments can be supplied or whether a declaration is well-formed.
Remember the trailing rule. - Statement I/II questions test inline functions:
inlineis a suggestion, ODR permits identical definitions in headers, and the compiler is not obliged to inline. - Match-the-list questions pair parameter forms (
int,int&,const int&,int*) with their modification and copying behaviour. - Assertion-reason questions frequently use returning a reference to a local variable as the classic undefined-behaviour assertion.
- Overloading questions check whether return type alone can distinguish overloads (it cannot) and whether default arguments can create ambiguity.
- Scope-resolution questions test global versus local shadowing and class-member definitions.
Practice at PARIKSHA
You are ready for the PARIKSHA tests of this sub-topic when you can:
- Explain the difference between a reference variable and a pointer, including initialisation, rebinding, and nullability.
- Trace a program that passes arguments by value, by pointer, and by reference, and state the exact output.
- Write a correct pointer-based swap and identify the bug in a wrong version that uses
int *temp. - Determine the output of code using default arguments and list all valid call signatures for a given prototype.
- State whether a given use of
inlineguarantees inlining and why. - Identify whether two function declarations form a valid overload or an illegal redefinition.
- Explain why returning a reference to a local automatic variable is dangerous and when returning a reference is safe.
- Use the scope resolution operator to access a shadowed global variable and to define a class member outside the class.
- Distinguish
const T&fromT&andT*in terms of copying and modification. - Analyse a match-the-list or assertion-reason question on parameter passing and return types.
Attempt the sub-topic test first, then the subject test.