β Status: Completed β all exercises
π« School: 42 β C++ Modules (Module 01)
π Score: 100/100
Memory allocation, references, pointers to members and
switchstatements.
This repository contains my solutions to 42βs C++ Module 01 (C++98).
Module 01 continues the C++ journey by focusing on:
- Dynamic memory and when to use heap vs stack
- References vs pointers (and how they differ)
- Pointers to member functions
- Using the
switchstatement in C++ - Structuring slightly larger examples while keeping code readable
All exercises are written in C++98 and compiled with strict flags (-Wall -Wextra -Werror -std=c++98).
Concepts covered (depending on the exercise):
- Manual memory allocation (
new/delete, arrays of objects) - Object lifetime and destructors (debug messages, leak-free code)
- References vs pointers and basic address manipulation
- Pointers to member functions (dynamic behavior without giant
if/elseforests) switch/casefor simple log-level filtering- Splitting code across multiple
.hpp/.cppfiles
The idea is to get comfortable with how C++ manages memory and indirection, while still staying in relatively small, focused exercises.
First zombie steps: stack vs heap allocation.
Goal:
Implement a Zombie class that:
-
Has a private
std::string name -
Has a member function
void announce(void);that prints:<name>: BraiiiiiiinnnzzzZ... -
Prints a debug message in its destructor when a zombie is destroyed
You also implement two helper functions:
-
Zombie* newZombie(std::string name);- Allocates a
Zombieon the heap, names it and returns the pointer
- Allocates a
-
void randomChump(std::string name);- Creates a temporary
Zombie, makes itannounce(), then lets it be destroyed
- Creates a temporary
Concepts practiced:
- Stack vs heap allocation and when each makes sense
- Constructors / destructors for debug output
- Ownership / lifetime of dynamically allocated objects
One zombie is nice. A whole horde is better.
Goal: Implement:
Zombie* zombieHorde(int N, std::string name);- Allocates
Nzombies in one allocation (array of objects) - Initializes all of them with the same
name - Returns a pointer to the first zombie in the horde
- You must
delete[]the horde when youβre done with it and ensure no leaks
Concepts practiced:
- Using
new[]/delete[]for arrays of objects - Looping through an array of objects and calling
announce() - Making sure destructors run for each element in the array
Demystifying references through addresses and values.
Goal: Write a program that:
-
Has a
std::stringinitialized to"HI THIS IS BRAIN" -
Declares:
stringPTRβ a pointer to that stringstringREFβ a reference to that string
-
Prints:
-
The memory address of:
- the original string
- the pointerβs target
- the referenceβs target
-
Then the values via:
- the variable
- the pointer
- the reference
-
Concepts practiced:
- Basic pointer and reference syntax
- Differences between pointers and references
- A reference is syntactic sugar with safety rules. It's like a "const pointer," which:
- Automatically dereferences (you don't need to write *).
- Prohibits NULL (the compiler will slap you if you try).
- Prohibits address changes (binding forever).
- Look how similar they are(pointers and references)
- Understanding that a reference is essentially an alias to an existing object
- Seeing how addresses line up in memory
Two humans, one weapon type: pointer vs reference design.
Goal:
Implement a Weapon class:
- Private attribute:
std::string type; const std::string& getType() const;void setType(const std::string& newType);
Then implement two classes: HumanA and HumanB:
-
Both have a name and some kind of Weapon association
-
Both implement:
<name> attacks with their <weapon type> -
Differences:
HumanAis always armed β theWeaponis passed in the constructor (likely as a reference)HumanBmay start unarmed and receive a weapon later viasetWeapon()(often stored as a pointer)
Concepts practiced:
- Choosing between reference and pointer members
- Understanding when an object must always exist vs may be optional
- Keeping weapon type in sync across multiple owners via reference/pointer
Tiny
sed-like replacer using only C++ strings.
Goal: Create a program:
./sed_is_for_losers <filename> <s1> <s2>- Opens
<filename> - Writes a new file
<filename>.replace - Replaces every occurrence of
s1withs2in the content - Handles invalid input and I/O errors
Important rules:
- You must not use
std::string::replace(depending on your chosen implementation style / subject constraints) - Use C++ streams (
std::ifstream,std::ofstream) instead of C-style I/O
Concepts practiced:
- File input/output with C++ streams
- Manual substring search + replace using string operations
- Edge cases: empty
s1,s2, large files, no matches, etc.
Turning a noisy customer into a table of function pointers.
Goal:
Implement a Harl class with private member functions:
void debug(void);void info(void);void warning(void);void error(void);
And a public function:
void complain(std::string level);This should:
- Call the corresponding private method based on
level("DEBUG","INFO","WARNING","ERROR") - Use pointers to member functions β no giant
if/else ifchains
The subject typically provides example messages for each log level.
Concepts practiced:
- Mapping strings β member function pointers
- Cleaner dispatch vs long condition chains
- Encapsulating logging behavior inside a class
Same Harl, but now with log-level filtering and
switch.
Goal: Create a program:
./harlFilter <level>-
<level>is one of:"DEBUG","INFO","WARNING","ERROR" -
The program prints all messages from that level and above, in order. For example:
-
Input:
"WARNING"β printsWARNING+ERRORmessages -
Input: invalid string β prints a default line like:
[ Probably complaining about insignificant problems ]
-
-
Executable name is usually
harlFilter -
You must use the
switchstatement for this exercise
Concepts practiced:
- Mapping strings to integer levels and using
switch - Filtering logs by severity level
- Reusing the
Harlclass and controlling which levels are displayed
General requirements for the C++ modules:
-
Compiler:
c++ -
Flags:
-Wall -Wextra -Werror-std=c++98
-
OS: any Unix-like system (Linux / macOS)
-
No external libraries (no C++11, no Boost, etc.)
-
No
printf,malloc,free& friends β use C++ standard library instead -
Do not use
using namespace std;(or any other namespace withusing namespace)
Clone the repository and build each exercise separately:
git clone <this-repo-url>
cd cpp-module-01cd ex00
make
./zombies # or whatever executable name you chosecd ex01
make
./hordecd ex02
make
./braincd ex03
make
./violencecd ex04
make
./sed_is_for_losers input.txt s1 s2cd ex05
make
./harlcd ex06
make
./harlFilter "WARNING"Exact executable names may differ depending on my implementation / subject instructions.
cpp-module-01/
βββ ex00/
β βββ Makefile
β βββ Zombie.hpp / Zombie.cpp
β βββ newZombie.cpp
β βββ randomChump.cpp
β βββ main.cpp
β
βββ ex01/
β βββ Makefile
β βββ Zombie.hpp / Zombie.cpp
β βββ zombieHorde.cpp
β βββ main.cpp
β
βββ ex02/
β βββ Makefile
β βββ main.cpp
β
βββ ex03/
β βββ Makefile
β βββ Weapon.hpp / Weapon.cpp
β βββ HumanA.hpp / HumanA.cpp
β βββ HumanB.hpp / HumanB.cpp
β βββ main.cpp
β
βββ ex04/
β βββ Makefile
β βββ main.cpp
β βββ *.hpp / *.cpp # helper classes if any
β
βββ ex05/
β βββ Makefile
β βββ Harl.hpp / Harl.cpp
β βββ main.cpp
β
βββ ex06/
βββ Makefile
βββ Harl.hpp / Harl.cpp # can reuse / adapt from ex05
βββ main.cpp
Some ideas for manual testing:
-
ex00 / ex01 β Zombies
- Verify destructors are called when expected (heap vs stack, horde deletion)
- Run with Valgrind / a leak checker to make sure there are no memory leaks
-
ex02 β HI THIS IS BRAIN
-
Check that all three printed addresses are consistent:
- string variable address
stringPTRtargetstringREFtarget
-
-
ex03 β Unnecessary violence
- Change the weapon type after constructing humans and ensure both see the updated value
- Test
HumanBwithout a weapon first to ensure it doesnβt crash and behaves predictably
-
ex04 β Sed is for losers
- Empty file, no occurrence of
s1 s1at the start/end of file and multiple times in a row- Edge case:
s1ands2having different lengths, ors1being an empty string
- Empty file, no occurrence of
-
ex05 β Harl 2.0
- Pass each log level and verify only the correct output appears
- Check behavior with invalid levels (should probably do nothing or handle it gracefully)
-
ex06 β Harl filter
-
Test each valid level (
DEBUG,INFO,WARNING,ERROR) and verify that:- It prints from that level upwards
-
Test with completely invalid strings:
- Should print something like
[ Probably complaining about insignificant problems ]
- Should print something like
-
- C++ modules have no enforced Norminette, but the subject still expects clean and readable code.
- No STL containers or algorithms before the later modules β stick to basic types and
std::stringfor now. - Headers must be self-sufficient (include their own dependencies) and properly guarded against multiple inclusion.
If youβre a 42 student working on the same module, feel free to browse the code and learn from it β but write your own implementation. Thatβs how youβll actually understand C++ and survive the exams. π