Methods

42 (XII): C++, the modules

From C to C++: classes, inheritance, polymorphism and overloading. The mindset shift

2 min read

After a year of strict C, where nothing is handed to you and every byte is yours to manage, the first week of C++ was a strange shock: std::cout (C++'s way of writing to the screen), std::string (text strings that manage themselves), classes that initialize themselves. I felt like I was cheating. Two hours later, the compiler had already taken care of shattering my illusion.

The problem

The C++ curriculum at 42 arrives in ten modules, cpp00 through cpp09, in the final stretch of the common core —the previous stop had been NetPractice, networks without a server— and it's not a syntax course: it's a mindset shift. In C you think in functions and memory; in C++ you design types. And 42, as always, sets rules that force you to understand the why: no printf, no malloc, none of the old-style casts. If you were going to use C++, it had to be real C++: streams, references, and an orthodox canonical form that every class must comply with —default constructor, copy constructor, assignment operator, and destructor— so it can be copied and destroyed without surprises.

How I tackled it

Module by module, with the Makefile (the file that tells the system how everything should be compiled) as a travel companion. Module 00 was classes and the canonical form. Module 01, allocation with new (C++'s way of requesting memory) and the real difference between pointers and references. Module 02, operator overloading: making a class addable, comparable, and incrementable as if it were a number. Module 03, inheritance, with the usual trap: what gets inherited and what doesn't. And module 04, the one that ties it all together: subtype polymorphism, abstract classes, and the rule that has stuck with me the most —the destructor must be virtual, because if you delete a derived object through its parent, without virtual not everything gets freed. In the repository my modules go up to here; the last ones, templates and containers, I worked through with reference material by my side. It doesn't weigh on me: a good part of these topics comes back, compressed, in the level 5 exam passed.

What I learned

That the C from the previous year wasn't dead weight: you know what an std::string does under the hood when you've built the memory handler yourself. That references aren't pointers in disguise: they're aliases with restrictions, and those restrictions are what give them value. That inheriting is easy, but polymorphism —a common interface that behaves according to the actual type— is the whole point of object-oriented design. And that now a three-line C++ compiler error message feels good to me: it tells me the type system is protecting me from a bug that, in C, would have surfaced at three in the morning.