Topic 2 of 27 · Beginner
Types, References & auto
Fundamental types, references, const and type inference.
Concept
C++ has the C types plus bool and std::string. auto deduces a variable's type from its initialiser.
A reference is an alias for an existing variable: it must be initialised and can't be reseated. Pass large objects by const reference to avoid copies.
Use brace initialisation int x{5}; it prevents narrowing conversions.
Cheat sheet
| Pass by | Copies? | Can modify? |
|---|---|---|
| Value (T) | Yes | Only the copy |
| Reference (T&) | No | Yes |
| Const ref (const T&) | No | No |
| Pointer (T*) | No | Yes, may be null |
Code (C++20)
#include <iostream>
#include <vector>
void doubleIt(int& x) { x *= 2; }
long long total(const std::vector<int>& v) {
long long s = 0;
for (int x : v) s += x;
return s;
}
int main() {
int a{10};
doubleIt(a); // a = 20
auto v = std::vector<int>{1, 2, 3};
std::cout << a << ' ' << total(v) << '\n';
// int bad{3.7}; // error: narrowing
}Remember
- References can't be null or reseated.
- const T& for read-only large params.
- Brace init blocks narrowing.
Interview questions
Pointer vs reference?
A pointer can be null, reassigned and does arithmetic; a reference must be bound at creation, can't be null and always refers to the same object.
What does const after a member function mean?
The function promises not to modify the object's state, so it can be called on const objects.
Lesson test
Take an 8-question test on “Types, References & auto” — concepts, output prediction, bug spotting and interview questions.