Encapsulation and week 5 review
To encapsulate means to hide the internal details of a class and expose only a small, safe interface. The reason is not privacy for its own sake, but protecting invariants: the conditions that must always hold for the object to make sense. A balance must never be negative, a date cannot have month 13, an empty stack has no top element. If the data is public, any part of the program can break those conditions and errors appear far from their cause. With private data and methods that validate, only the class has to be correct, and that is reviewed in a single place.
Invariants and the minimal interface
Designing an interface means deciding which operations make sense, not which fields exist. An integer Stack class should not offer access to its internal vector, but push, pop, top, empty and size. Notice that pop and top must decide what to do if the stack is empty: here we throw std::out_of_range, which is a clear signal that the program misused the class. Avoid automatic get/set pairs for every field: a setter that accepts any value is almost as bad as a public field. Offer operations with domain meaning, such as deposit and withdraw, instead of setBalance.
#include <iostream>
#include <stdexcept>
#include <vector>
class Stack {
public:
void push(int value) { items_.push_back(value); }
void pop() {
if (items_.empty()) {
throw std::out_of_range{"pop on empty stack"};
}
items_.pop_back();
}
int top() const {
if (items_.empty()) {
throw std::out_of_range{"top on empty stack"};
}
return items_.back();
}
bool empty() const { return items_.empty(); }
std::size_t size() const { return items_.size(); }
private:
std::vector<int> items_; // the representation can change without breaking users
};
int main() {
Stack s;
s.push(10);
s.push(20);
std::cout << s.top() << ' ' << s.size() << '\n'; // 20 2
s.pop();
s.pop();
try {
s.pop();
} catch (const std::out_of_range& e) {
std::cout << "error: " << e.what() << '\n'; // error: pop on empty stack
}
return 0;
}Static members and operator<<
A static member belongs to the class, not to each object: there is a single shared copy. It is used for counters, class constants or helper functions that do not need an object. Since C++17 you can declare it inline inside the class and avoid the separate definition: static inline int created_{0};. Another useful piece is operator<<, which lets you print your objects with std::cout. It is written as a free function, not a member, takes the stream by reference and returns it so calls can be chained. If it needs to read private members, the clean way is for the class to offer a const method, like toString.
#include <iostream>
#include <string>
#include <utility>
class Ticket {
public:
explicit Ticket(std::string title)
: id_{++created_}, title_{std::move(title)} {}
int id() const { return id_; }
std::string toString() const { return "#" + std::to_string(id_) + " " + title_; }
static int totalCreated() { return created_; }
private:
static inline int created_{0}; // shared by every Ticket
int id_;
std::string title_;
};
std::ostream& operator<<(std::ostream& os, const Ticket& t) {
return os << t.toString();
}
int main() {
Ticket a{"Fix login"};
Ticket b{"Update docs"};
std::cout << a << '\n' << b << '\n';
// #1 Fix login
// #2 Update docs
std::cout << "total = " << Ticket::totalCreated() << '\n'; // total = 2
return 0;
}Week summary: a class groups data and operations; the constructor leaves the object in a valid state, preferably with an initializer list; the destructor releases resources and, with RAII, cleanup is automatic; private members protect invariants; const methods document that they do not modify the object. A common review mistake: forgetting const on a reading method and later discovering it cannot be called on a const object. Another: initializing members in a different order than declared and getting compiler warnings. Always enable -Wall -Wextra and treat warnings as study errors.
जो सीखा उसे परखें
प्रश्न 1 / 6What is encapsulation mainly for?
✎ मेरे नोट्स
केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर