C++
Beginner
1 min read
References, Pointers, and Value Semantics
Example
#include <iostream>
#include <string>
// Pass by value: a copy is made
void byValue(std::string s) {
s += " (modified)";
std::cout << "inside byValue: " << s << "\n";
}
// Pass by reference: no copy, caller sees changes
void byRef(std::string& s) {
s += " (modified)";
}
// Pass by const reference: no copy, read-only
void byConstRef(const std::string& s) {
std::cout << "inside byConstRef: " << s << "\n";
}
int main() {
std::string original = "Hello";
byValue(original);
std::cout << "after byValue: " << original << "\n"; // unchanged
byRef(original);
std::cout << "after byRef: " << original << "\n"; // modified
byConstRef(original);
// Pointer example
int x = 42;
int* ptr = &x; // ptr stores the address of x
std::cout << "x via pointer: " << *ptr << "\n";
*ptr = 100; // dereference to modify
std::cout << "x after write: " << x << "\n";
// Reference example
int& ref = x;
ref = 200; // same as x = 200
std::cout << "x via ref: " << x << "\n";
return 0;
}