References and classes
C++ gives you value semantics by default and references for aliasing.
What you will be able to do
- Prefer const T& for read-only parameters of non-trivial types.
- Use std::string and std::vector instead of raw arrays and char buffers.
- Mark methods const when they do not change the object.
In plain English
A reference is an alias to an existing object and cannot be reseated. Passing by const reference avoids copies without allowing mutation. A class should protect invariants through its interface, not through public fields.
#include <iostream>
#include <string>
#include <vector>
class Course {
public:
Course(std::string slug, int lessons)
: slug_(std::move(slug)), lessons_(lessons) {}
const std::string& slug() const { return slug_; }
int lessons() const { return lessons_; }
private:
std::string slug_;
int lessons_;
};
void print(const Course& course) {
std::cout << course.slug() << ": " << course.lessons() << " lessons\n";
}Your turn
MediumEncapsulate a score
Create a Score class with a private value and a method that clamps additions at 100.
CPP · starter
class Score {
public:
int value = 0;
};Check your understanding before moving on.
Knowledge checkQuestion 1
What does a const reference parameter prevent?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.