Menu
CoddyTech

Protecting Invariants

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

C libraries often hide struct definitions behind opaque pointers. C++ private fields enforce access within the type while public methods protect invariants. Getters expose a chosen view of state; returning a writable reference can accidentally bypass the validation policy.

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct Name {const char* text;};int set_name(struct Name* n,const char* s){if(!*s)return 0;n->text=s;return 1;}
int main(void){
struct Name n={""};int a=set_name(&n,"");int b=set_name(&n,"oak");printf("%s %s %s\n",a?"true":"false",b?"true":"false",n.text);
return 0;
}

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

Practice on your own: Online C++ compiler