Access Control, const and friend
public, protected and private control access. const methods promise not to change the object, and friend grants another function or class access to private members.
Example
#include <iostream>
using namespace std;
class Acct {
int bal = 0;
public:
void dep(int n) { if (n > 0) bal += n; }
int get() const { return bal; }
friend void audit(const Acct &a);
};
void audit(const Acct &a) { cout << "audit " << a.bal << "\n"; }
int main() { Acct a; a.dep(50); cout << a.get() << "\n"; audit(a); }Result
50 audit 50
Exercise
Method that does not modify the object.
int get() { return x; }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.