Menu
CoddyTech

Protecting Invariants

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

Java access modifiers and encapsulation transfer conceptually, but C++ friendship and value semantics alter interface design. C++ private members enforce access control. Expose operations that preserve invariants instead of writable references to private state.

Java

import java.util.*;
public class Example {
  static class Box { private int n; Box(int n) { this.n=n; } int getDouble() { return n*2; } }
  public static void main(String[] args) {
    System.out.println(new Box(3).getDouble());
  }
}

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 Java Developers

Practice on your own: Online C++ compiler