C++ · 2 · Classes & RAII9 / 36 · 25%
Access Control, static & friend
Encapsulation knobs: who can touch what, and what belongs to the class itself.
Examples: public/private/protected, static members, friend
shortcuts: ← prev · → next · M mark
1
Access Specifiers
struct defaults to public, class defaults to private.
Example
example
class Account {
public:
void deposit(double x); // interface
protected:
void audit(); // derived classes only
private:
double balance_ = 0; // nobody outside
};2
static Members
One shared instance for the whole class, not per object.
Example
example
class Counter {
static inline int live_ = 0; // C++17: define inline in the header
public:
Counter() { ++live_; }
~Counter() { --live_; }
static int live() { return live_; } // no this pointer
};3
friend
Grants one specific function or class access to privates.
Example
example
class Vec2 {
float x_, y_;
friend std::ostream& operator<<(std::ostream&, const Vec2&);
};
std::ostream& operator<<(std::ostream& os, const Vec2& v) {
return os << '(' << v.x_ << ", " << v.y_ << ')';
}TIP
friend is not a hole in encapsulation when used for operators that are logically part of the class.
4
explicit & Member Init
Stop accidental implicit conversions; initialise in the member list.
Example
example
class Buffer {
std::size_t size_;
std::vector<char> data_;
public:
explicit Buffer(std::size_t n) : size_(n), data_(n) {}
// without explicit: Buffer b = 42; would compile
};Members initialise in declaration order, not the order you write in the init list.