Menu
CoddyTech

Protecting Invariants

Lesson 36 of 48 in Coddy's C++ for Lua Developers course.

Lua has no private fields: anyone can assign to any key of a table, so a leading underscore is only a convention. True privacy in Lua comes from closures, where the state lives in an upvalue that only the returned functions can reach. C++ private fields are enforced at compilation. C++ private members enforce access control. Expose operations that preserve invariants instead of writable references to private state.

Lua

local function Meter(level)
  local self = {}
  function self.get()
    return level
  end
  function self.set(value)
    if value < 0 then
      error("negative")
    end
    level = value
  end
  return self
end
local m = Meter(3)
local ok = pcall(m.set, -1)
print(tostring(ok) .. " level=" .. m.get())

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
class Name {std::string text_;public:bool set(const std::string& s){if(s.empty())return false;text_=s;return true;}std::string get()const{return text_;}};
int main(){
Name n;std::cout<<std::boolalpha<<n.set("")<<" "<<n.set("oak")<<" "<<n.get()<<"\n";
}

Trace each program independently. These examples demonstrate the concept with different operations or data from the task; source and target output are not assumed to match.

challenge icon

Challenge

Easy

Input: initial nonnegative capacity then requested withdrawal. Stock.take accepts a nonnegative amount only if enough remains, returns success, and otherwise leaves state unchanged. Print success as true/false then remaining.

Editable modules: Stock.cpp, Stock.hpp. Each required type has its own named header and implementation. Preserve all public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#include "Stock.hpp"
#include <iostream>
int main(){
{Stock s(5);if(!s.take(2)||s.take(4)||s.take(-1)||s.remaining()!=3||!s.take(3)||s.remaining()!=0)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n,k;in>>n>>k;Stock s(n);bool ok=s.take(k);std::cout<<std::boolalpha<<ok<<" "<<s.remaining()<<"\n";
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C++ for Lua Developers

Practice on your own: Online C++ compiler