References in C++
References provide an alias for existing variables. Syntax: DataType &alias = originalName; References must be initialized and cannot be reassigned.
#include <iostream>
using namespace std;
int main() {
int x = 15;
int &y = x;
cout << x << endl; // 15
cout << y << endl; // 15
y = 25;
cout << x << endl; // 25
int z = 30;
y = z; // Assigns value, doesn't change reference
cout << x << endl; // 30
}
1.1 References as Function Parameters
When used as parameters, references can modify the original arguments.
void increment(int &num) {
num++;
}
int main() {
int val = 5;
increment(val);
cout << val; // 6
}
1.2 Returning References from Functions
Avoid returning references to local variables. Function calls can be lvalues.
int& getMax(int &a, int &b) {
static int result = (a > b) ? a : b;
return result;
}
int main() {
int x = 10, y = 20;
getMax(x, y) = 50; // Modifies the static variable
}
1.4 Constant References
Prevent modification of referenced values.
void print(const int &val) {
cout << val;
// val = 10; // Error
}
Advanced Function Features
2.1 Default Parameters
Parameters can have default values. Once a default parameter appears, all following parameters must have defaulst.
int calculate(int a, int b = 5, int c = 10) {
return a + b + c;
}
2.2 Placeholder Parameters
Parameters without names can be used as placeholders.
int operation(int a, int) {
return a * 2;
}
2.3 Function Overloading
Multiple functions can share the same name with different parameters.
void display(int num) { /*...*/ }
void display(double num) { /*...*/ }
void display(int a, double b) { /*...*/ }
2.4 Overloading Considerations
References and const qualifeirs effect overloading. Default parameters can cause ambiguity.
void process(int &val) { /*...*/ }
void process(const int &val) { /*...*/ }