References#
A reference is an alias - a second name for an existing variable. It is declared with & after the type and must be initialised:
marks = 85, m = 85 Same address? yes
Reference किसी variable का दूसरा नाम है (जैसे किसी का घर का नाम)। int &m = marks; के बाद m और marks एक ही memory को दर्शाते हैं - m बदला तो marks भी बदल गया। Reference बनाते समय ही उसे किसी variable से जोड़ना ज़रूरी है और बाद में उसे बदला नहीं जा सकता।
| Pointer | Reference | |
|---|---|---|
| Syntax | int *p = &x; then *p |
int &r = x; then just r |
| Can be null | yes | no |
| Can point elsewhere later | yes | no (bound forever) |
| Typical use | dynamic memory, optional values | function parameters, aliases |
Pass by value vs pass by reference#
After copy version: 60 After reference version: 65
The reference version changes the caller's variable - like C pointers, but cleaner: no & at the call, no * inside.
const references - fast and safe#
Copying a big object (a long string, a vector of 1 lakh items) is slow. Pass it by const reference: no copy, and the compiler stops you from changing it.
Vowels: 10
Rule of thumb: pass small types (int, double, char) by value; pass strings, vectors and objects by const & if you only read them, and by & if you need to modify them.
Function overloading#
In C every function needs a unique name. In C++ several functions can share a name if their parameter lists differ (number or types). The compiler picks the right one from the arguments:
5 5.6 6 Vindhyaedu
Two functions that differ only in return type (int f(int) and double f(int)) are an error - the compiler cannot tell which one you mean from the call.
Default arguments#
Parameters can have default values, used when the caller leaves them out. Defaults must be at the end of the parameter list:
1180 1062 945
inline functions#
inline suggests that the compiler paste the function body at the call site instead of making a real call - useful for tiny, frequently called functions. Modern compilers decide this themselves, so inline today mainly allows a function to be defined in a header file.
inline int square(int x) { return x * x; }
Lambdas - small unnamed functions#
A lambda is a function you write right where you need it - very common with STL algorithms:
81 75
[ ] is the capture list (which outside variables the lambda can use), ( ) the parameters, { } the body.
Summary#
- A reference (
int &r = x;) is an alias; pass by&to modify, byconst &to read big objects without copying. - Overloaded functions share a name but differ in parameters.
- Default arguments fill in trailing parameters.
- Lambdas are inline, unnamed functions:
[capture](params) { body }.