Skip to content

Latest commit

 

History

History
155 lines (117 loc) · 17.2 KB

README.md

File metadata and controls

155 lines (117 loc) · 17.2 KB

C++ Modules

C "enhanced, enhanced"

GitHub code size in bytes Code language count GitHub top language GitHub last commit


📯 General info

  • We have to use C++98 and compile with the -std=c++98 flag (be careful, the macOS c++ compiler sometimes doesn't warns you if you're using newer features, so make sure to compile on Linux to be safe)
  • No norm 🥳
  • Class names must be in UpperCamelCase format. Files containing class code will always be named according to the class name.
  • You are allowed to use almost everything from the standard library. Thus, instead of sticking to what you already know, it would be smart to use as much as possible the C++-ish versions of the C functions you are used to.
  • Forbidden: Boost libraries, *printf(), *alloc(), free(), using namespace <ns_name> (but using <namespace>::<class> is allowed), friend keyword
  • Containers and Algorithms (<algorithm> header) are only allowed in Module 08 and 09
  • Avoid memory leaks
  • From Module 02 to 09, your classes must be designed in the Orthodox Canonical Form, except when explicitely stated otherwise
  • No function implementation in a header file
  • Headers must have include guards

Jump to module

CPP 00

Namespaces, classes, member functions, stdio streams, initialization lists, static, const, and some other basic stuff

Exercise Desription Learnings
00: Megaphone
  • Print the arguments in upper-case
  • what's a namespace
  • std::string
  • printing with std::cout
  • for loop
01: My Awesome PhoneBook
  • PhoneBook class with 8 Contacts that can ADD, SEARCH and EXIT
  • A Contact has: first name, last name, nickname, phone number, and darkest secret
  • ADD: prompts the user for Contact fields and it gets saved in the phonebook
  • SEARCH: display a list of all contact names with indexes, prompt for an index to print the corresponding contact
  • class syntax
  • public and private variables/methods
  • static functions
  • constructor and destructor
  • operator << overloading
  • default function arguments
  • reading a line from stdin using std::getline
  • do while loop
  • more std::string methods
02: The Job Of Your Dreams
  • Recreate a Account.cpp file from a Account.hpp file to produce the correct output
  • Print deposits, withdrawals and status of an account
  • total statistics are tracked as well
  • static variables
  • time formatting with std::strftime

CPP 01

Memory allocation, pointers to members, references, switch statement

Exercise Desription Learnings
00: BraiiiiiiinnnzzzZ
  • Zombie with name can announce himself
  • newZombie returns a heap allocated Zombie
  • randomChump makes a new Zombie that announces himself
  • initializer list on an argument constructor
  • class pointers
  • new keyword to allocate
  • delete to free the memory
01: Moar brainz!
  • zombieHorde returns a heap allocated array of Zombies
  • allocating arrays using new
  • using getters and setters for private variables rather than making them public
02: HI THIS IS BRAIN
  • Print addresses and values of string, string reference and string pointer
  • what's a reference and how it compares to a pointer
03: Unnecessary violence
  • HumanA and HumanB classes both have a Weapon
  • HumanB may not always have a Weapon, whereas HumanA will always be armed
  • Solution: HumanA has a reference to Weapon and HumanB has a pointer to Weapon (which can be NULL)
  • When to use pointers vs references
04: Sed is for losers
  • Creates a copy of the file in the argument with each occurence of a given string replaced by another
  • std::string::replace is forbidden
  • working with files using std::ifstream and std::ofstream
  • std::string methods i.e. erase, substr
05: Harl 2.0
  • Harl (aka Karen) can complain on the four levels "DEBUG", "INFO", "WARNING" and "ERROR", that just print out a message
  • You must use pointers to member functions and it is forbidden to make a large if/else tree
  • how to work with pointers to member functions
06: Harl filter
  • Prints all messages from the given level and above
  • switch statement and "fall-through"

CPP 02

Ad-hoc polymorphism, operator overloading and Orthodox Canonical class form

Exercise Desription Learnings
00: My First Class in Orthodox Canonical Form
  • simple Fixed class with integer for raw bist
  • static variable defines number of fractional bits to always 8
  • Orthodox Canonical Form
  • copy constructor
  • copy assignment overload
01: Towards a more useful fixed-point number class
  • int and float construcors
  • toFloat and toInt conversion methods
  • operator << overload for printing Fixed as a float
  • conversion between Fixed and other types using bit-shifting, math and roundf
02: Now we’re talking
  • overoads for comparison operators: >, <, >=, <=, == and !=
  • overoads for arithmetic operators: +, -, * and /
  • overoads for increment/decrement operators (both pre and post)
  • static min and max methods with both const and non-const arguments
  • good practice to make comparison operators depend on each other
  • how pre and post increment/decrement operators work on system level
  • ternary operator
  • printing boolean as a word using std::boolalpha
03: BSP
  • BSP stands for Binary space partitioning, though I didn't use that as it isn't really efficient for this use case
  • Point has const Fixed x and y variables
  • reconstruction in the copy assignment operator
  • checks if point is in triangle using vector formular
  • what's reconstruction and why to avoid it
  • always check if an algorithm is as efficient as possible for your specific use case

CPP 03

Inheritance

Exercise Desription Learnings
00: Aaaaand... OPEN!
  • ClapTrap class with name, health, energy and damage private attributes
  • attack, takeDamage and beRepaired methods alter the attributes and print a pretty message
  • simple exercise but I tried allocating an object for the first time
01: Serena, my love!
  • ScavTrap inherits ClapTrap but has different values
  • overloads attack method for specific print message
  • adds guardGate method for printing a message
  • inheritance syntax
  • virtual keyword for making a base class method overloadable
  • why having a virtual destructor is important
02: Repetitive work
  • FragTrap inherits ClapTrap with different values again
  • adds highFivesGuys method for printing a message
03: Now it’s weird!
  • DiamondTrap inherits both ScavTrap and FragTrap
  • adds name attribute and adds suffix to ClapTrap's name
  • uses health and damage from FagTrap and energy, as well as attack method from ScavTrap
  • adds whoAmI method that prints name and ClapTrap's name
  • ClapTrap subobject must only be created once
  • Diamond Problem when doing multiple inheritance
  • using keyword to choose from which subclass to take method
  • virtual inheritance to only create one subobject

CPP 04

Subtype polymorphism, abstract classes, interfaces

Exercise Desription Learnings
00: Polymorphism
  • simple Animal class gets inherited by Dog and Cat classes
  • Animal has makeSound method that prints nothing, but Dog and Cat overrides the function to print an applicaple message
  • WrongAnimal and WrongCat proove understanding of method overriding
  • implicitly casting pointer of derived class to pointer of base class
  • deepened the knowledge of the virtual keyword
01: I don’t want to set the world on fire
  • Brain class has an array of std::string ideas
  • Dog and Cat get pointer to Brain attribute that gets allocated on construction and freed on destruction
  • copy of ideas must be deep copies
  • why constructors and destructors are awesome for managing allocated memory
02: Abstract class
  • Animal's makeSound method is made pure virtual
  • pure virtual functions make classes abstract and non-instantiable, derived classed need to provide implementation if instatiation is desired
03: Interface & recap
  • Ice, Cure, Character and MateriaSource inherit provided abstract class AMateria and interfaces ICharacter and IMateriaSource respectively
  • they all have attributes and methods that take the objects (pointers) as arguments
  • pure abstract classes are called 'interfaces' even though they don't exist as a data structure in C++ as in other programming languages
  • more working with object pointers and references, as well as arrays and memory allocation with classes

CPP 05

Repetition and Exceptions

Exercise Desription Learnings
00: Mommy, when I grow up, I want to be a bureaucrat!
  • Bureaucrat class with grade attribute and increment/decrement methods
  • if a Bureaucreat is constructed or the grade is increment/decrement beyond the range, a Bureaucrat::GradeTooHighException or Bureaucrat::GradeTooLowException are thrown
  • exceptions for handling errors
  • writing my own exception class that overrides the what function, which provides the reason for the exception
  • throw keyword, can also throw simple data types, though std::exception is preferred
  • try catch block
01: Form up, maggots!
  • Form class has name, isSigned, signGrade and executeGrade attributes
  • has beSigned method that signs the form if the grade of the Bureaucrat is valid according to the Form attributes, otherwise throws exceptions
  • signForm method is added to the Bureaucreat that calls beSigned on the provided From
02: No, you need form 28B, not 28C...
  • Form gets pure virtual execute method that makes the class abstract
  • ShrubberyCreationForm, RobotomyRequestForm and PresidentialPardonForm are derived from AForm with different values and implementation for the execute method
  • adds executeForm to the Bureaucrat
03: At least this beats coffee-making
  • Intern class has a makeForm method that takes a name of a form and returns a pointer to the correct heap allocated object

CPP 06

C++ casts

Exercise Desription Learnings
00: Conversion of scalar types
  • ScalarConverter class contains static method convert which converts a string representation of char, int, float and double as literal to all four data types and prints them out
  • pseudo literals inf (positive or negative) and nan, both float (inff) or double, have to be handled as well
  • static_cast to change the datatype and keep the value
01: Serialization
  • Serializer class has two static methods: serialize converts Data pointer to uintptr_t, deserialize converts uintptr_t to Data pointer
  • Data is just an example class to proove that it works
  • reinterpret_cast changes the data type but keeping the exact same value
02: Identify real type
  • A, B, C classes are derived from Base class
  • generate function returns a random class as a Base pointer
  • identify prints the name of the derived class - has two implementations, one taking a Base pointer, the other taking a Base reference
  • dynamic_cast to cast at runtime
  • returns NULL when casting pointer, throws exception when casting object (reference)

CPP 07

C++ templates

Exercise Desription Learnings
00: Start with a few functions
  • swap template function swaps the two given arguments
  • min and max template functions return the right value
  • template syntax
01: Iter
  • iter template function iterates over an array of any type and applies the provided function to each element
02: Array
  • Array template class has pointer that allocates an array of the provided type with the size provided at construction
  • operator [] overload lets you access elements inside the array
  • throws exception if index is out of bounds
  • template classes

CPP 08

Templated containers, iterators, algorithms

Exercise Desription Learnings
00: Easy find
  • template function easyfind takes any container on integers and returns an iterator to the provided integer
  • what are containers and iterators
  • std::find algorithm to do the job
01: Span
  • Span class has a std::vector of integers with the maximum size specified on construction
  • addNumber and addRange (using iterators) let you add numbers to the vector
  • shortestSpan and longestSpan calculate the distance between any numbers in the vector
  • std::sort for faster calculation of the shortest span
  • std::min_element and std::max_element for very easy calculation of longest span
02: Mutated abomination
  • template class MutantStack inherits from std::stack (defaults to std::deque container) and adds iterator and const_iterator
  • begin and end methods return the corresponding iterator
  • multiple typenames for a template class
  • how iterators work in more detail

CPP 09

STL

Exercise Desription Learnings
00: Bitcoin Exchange
  • btc program takes file as argument which is a list of dates and values
  • prints the value multiplied the exchange rate according to the date indicated in a database 'csv' file
  • std::map for key-value pairs
  • std:lower_bound returns the first element smaller than value
  • std::string::compare
  • std::runtime_error for clean exception throwing
  • overall working on a larger project with many C++ features
01: Reverse Polish Notation
  • RPN program takes string of digits and operations +, -, * and / and calculates the result in Reverse Polish Notation
  • what Reverse Polish Notation is
  • std::stack is ideal for pushing numbers ontop then popping and calculating the top two when there is an operation and pushing pushing the result back
02: PmergeMe
  • PmergeMe program takes a positive integer sequence and uses merge-insertion-sort aka Ford Johnson algorithm on two containers to print a sorted sequence as well as the time it took
  • algorithm: splits sequence into pairs, sorts each pair, recursively merge-sorts the pairs according to the first value, creates a sequence of all firsts of the pairs, uses Jacobsthal sequence to efficiently insert the sequence of seconds of the pairs into the result sequence using insertion-sort
  • Ford Johnson algorithm is one of the best when it comes to low number of comparisons
  • what's the Jacobsthal sequence and why does it make the algorithm efficient
  • std::vector and std::deque with their methods
  • std::upper_bound which is implemented as binary-search (required for insersion-sort)

Made it! 🥵