Friday, 30 October 2015

Low-Level Programming_Post6

Low-Level Programming: Post 6 29/10/15

October 29th 2015 is the date of the sixth lesson on Low-Level Programming.

At the start of the lesson, we were given, as usual, an overview of what we were going to learn today. The following bullet points are the list of features that were taught in the lesson (including a guide as to how to make the practical from last week work and how it should have been done)...

  • Libs: Last week's practical reviewed.
  • Container: Vectors, Arrays, Linked Lists and Deques i.e. non-associative.
  • Iterators: What they are and how they work.
  • Erase-Remove Idiom: How to search and erase elements in containers provided by the STL.
Before we began working on the bullet points above, there we three 'important pieces of information' given to us.

The first 'piece of information' was on how the lessons were going to be covered from next week onwards. It said that in the three hour lesson(s), one hour will go into the concepts (lecture) and the other two will go into the practicals. We were also told/recommended to go and work/practice on any pieces of work that were provided to us over the past few weeks, since there isn't enough time to cover everything in extensive detail.

The second 'piece of information' was essentially a recap on Shared_Ptrs, Weak_Ptrs, Casting and Implicit Casting. Since we have covered the above points in the past two posts, I won't be going into extensive detail again on them.

The third, and unquestionably the most important 'piece of information' was the assignment brief given to us. It covered the marking scheme and expectations for the first part of the assignment. It goes as follows...

  • 75% Portfolio: Portfolio of Tasks, Assignments and Practical Work.
  • 40& Exercise One: 40% of the 75% for this one, with the instructions on Blackboard.
The next part covered the deliverables necessary for the assignment...
  • A Single Executable Running.
  • A Menu System.
  • And the Three Games Required.
  • The Three Games listed above are Blackjack, Hangman and Snake.
The most crucial part of the brief was perhaps the breakdown of the assignment...
  • 10% for the Coding Style.
  • 10 % for the Menu System: Console Based, the System should be the first point of entry into your game.
  • 15% for the Object-Oriented Programming.
  • 15% for Blackjack: Implementing the game and meeting the grading criteria. This game shouldn't pose too many problems as it's rules are simple.
  • 20% for Hangman: Should be trickier than Blackjack but still achievable.
  • 30% for Snake: The trickiest game of the three, hence it carries more marks. At least attempts at marks are awarded for coding design decisions.
The last part of the brief was a general guidance on how to work on the assignment...
  • Console: Don't focus on graphics; this assignment is all about code design and OPP decision making. I.e. Correct usage of inheritance and memory.
  • Try: Do try to complete all three game. Even if the game isn't fully working, there are marks for the design of the games.
  • Easy Marks: Just following the Coding Style gets you 10%, not to mention the Menu System another 10%.
  • Tutorials: Whilst the tutorials won't tell you exactly how to resolve all the gameplay mechanics, you will get the chance to work with the elements needed to complete the task.
  • Attendance: Skipping lectures and tutorials will do you no favours in the long run. It's the opportunity to practice the concepts.
After the assignment brief, we were given a guide as to how the practical from last week's lesson should have worked. I managed to get most of the instruction guides. They are as follows...
  • Create a New Project.
  • Select Console Application.
  • Do NOT include two 'additional options'.
  • Open File in File Explorer.
  • Copy 'Libcaca' (name of project) into project.
  • #include 'caca.h' -> Error.
  • Go into Project Properties.
  • Additional, include dependencies/directions.
  • #include 'caca.h'
  • #include <iostream>
  • Go into Project->Linker->All Options.
  • Additional Library Directions.
  • X86 -> Debug.
  • Full Stop, not Comma.
  • Add Void ShowMessage(); before Main.
  • Add ShowMessage(); IN Main.
Now that the parts before on what we were going to learn finished, we started on learning on the bullet point features. As it always is, I will not be going over past features (in this case, a basic Vectors recap).
Vector: Common Operations
  • Iterators:
  • begin & cbegin - Iterator to First Element.
  • end & cend - Iterator to Last Element.
  • rbegin & crbegin - Reverse Iterator to First Element.
  • rend & crend - Reverse Iterator to Last Element.
Vector: Reverse Iterator
  • Reverse Iterator: Reverse Iterators traverse backwards through the array. And they also support const.
Vector: Capacity
  • Size: We can find out the size of the array.
  • Capacity: We can check the capacity of the array.
  • Reserve: We can reserve a block of memory for X objects.
Vector: In Summary
  • Arrays: A good alternative to traditional arrays in C and C++.
  • Performance: Shows efficient and fast performance when iterating through the array.
  • Memory: Contiguous memory usage benefits caching and prevents fragmentation.
  • Memory Allocation: Dynamic reallocation is powerful but also slow, so reserve a reasonable amount of space up front.
  • Iterators: Provides iterators and individual access using [] operator.
Iterators
  • What Are They?: An Iterator is any object that points to an element in a container and has the ability to iterate through the container's range.
  • Operation: Usage of the increment (++), decrement (--) and deference (*) operations.
  • Pointer: A raw pointer can be thought as an iterator, due to it's ability to increment and decrement i.e. pointer arithmetic.
  • Behaviour: A pointer is a type of iterator, but not all iterators work the same way as pointers.
  • Types:
  • Input.
  • Output.
  • Forward.
  • Bidirectional.
  • Random Access.
Erase-Remove Idiom
  • What is it?: A C++ technique to remove container elements that fulfill certain conditions.
  • Loops: It's possible to achieve the same behaviour by using loops to locate elements to erase. but this is considered simpler.
  • C++ Std: Provides us with two algorithms that can be used to remove elements, Remove and remove_if.
  • Iterators: They use iterators to determine the range that should be erased (2x forward iterators).
  • Restructures: In order to ascertain the begin and end iterators, the container has to be re-arranged.
  • Erase: The two remove algorithms do not erase the elements, the result is normally passed to an erase function.
Erase-Remove Idiom: Performance
  • Removal: As remove and remove_if do not actually erase the items, but does move valid data, there must be some sort of overhead.
  • Operation: In modern C++ the elements that are valid are moved to the front of the container. However, the elements to be deleted are not, this means they have an undefined but valid state.
  • Distance: Performance of the algorithm is determined by the number of elements in it, though iteration (linear) should be a constant, the moving of the data is unknown.
  • Erase: Don't forget to erase the results of remove function as the end of the array could be invalid. The erase-remove idiom comes from having to remove first before erasing.
Predicates
  • Unary Predicates: STL algorithms often use predicates to accomplish tasks; such as remove.
  • Return: Simply unary predicates are functions that take a single parameter and return a Boolean.
  • C++ Std:We've seen already that remove_if utilises predicates to determine whether the element should be moved.
  • Iterators: The predicate should take an iterator and deference it for usage within the function.
  • Constant: The dereferenced object should not have any non-constant function called and must not invalidate iterators that the algorithm uses.
  • Index Agnostic: The predicate should also not care about the order of elements tested or their position.
Std::Array
  • Fixed Size Array: STL container that encapsulates fixed size arrays.
  • Functionality: Designed to allow the simplicity and of an array but with support for the std algorithms and iterators.
  • Performance: Has the same performance as a C style array.
Linked Lists
  • Nodes: Linked Lists consist of nodes that link to each other. Forward lists utilise a next node ptr, to traverse both ways you need a prev node ptr.
  • Disparate: The memory is allocated on a node by node basis. No guarantee is made to their location, thus potentially causing cache misses.
  • Agnostic: As long as a node has a ptr to the next item in the list, the items they point to can be of any type.
  • Removal: Removal of nodes causes a deallocation and then an update of the prev node, thus preventing wasted memory space.
  • Dynamic Allocation: Prevents the overheads inherent in resizing arrays dynamically, i.e. allocation and then moves from one location to another.
  • Constraints: You don't need random access to the elements and memory allocation/deallocation is more vital than cache misses.
Linked Lists: In Operation
  • Adding/Removing: You can break the chain and add or remove new items easily.
  • Performance: No overhead other than an allocation or deallocation when working with nodes.
Deque
  • Double Ended: Sequence containers that can be expanded or contracted on both ends (front or back).
  • Functionality: In terms of functionality, they work in a similar fashion to vectors, but they allow manipulation of items at both ends.
  • Adding/Removing: They are efficient when removing or adding elements to either end of the array.
  • Expansion: Like vectors, they can expand or contract and this is performed dynamically.
  • Memory: Vectors guarantee contiguous blocks of memory but deques do not.
  • Performance: They can grow more efficiently than vectors and are suited to tasks with lots of insertions or removals.
Deque: Workings
  • Vector vs Deque: Vectors are contiguously allocated in memory, deques do not operate in the same manner.
When the lectural side of the lesson, along with the break finished, we had to work on the DungeonDeath game once again. Since I was working alone this weak, I was not making a lot of progress. I did manage to, however, add some more rooms to the level and fix the exit game option, since it left a 'This room is blocked' comment when closing the program down.

Thursday, 22 October 2015

Low-Level Programming_Post5

Low-Level Programming: Post 5 22/10/2015

October 22nd 2015 is the date of the fifth lesson on Low-Level Programming.

In today's lesson, we began with the traditional overview of what we were going to learn today, with the first point a review of what we learnt last week (Static and Dynamic Casting). However, before we began the slides, we were tasked to 'peer review' other people's blogs. However, my table only viewed one out of the four dev blogs, as we started discussing about 'Cache Coherency'.

After reviewing the blog, we were given the official marking and expectations for the module. 75% of the marks go towards the portfolio (Portfolio of tasks and Assignments/Practical Work) and 25% of the marks go towards the dev blogs (Tracking of Learning and that the dev blogs are completed on a daily basis).

The following points are what we learnt in the lesson...

  • Memory: Automagic Pointers, Deep Copies, Virtual Destructors.
  • Containers: Structs and Vector.
  • Libraries: Practical Work involving the use of a third-party library.
Similar to last week, I will not be going over what we reviewed (as that is on last week's post). Therefore, I will be starting with Memory.

Memory Management/Class Cleanup
  • Class Memory: When we create classes, there's a good chance it's going to store some sort of data regarding it's state.
  • Inheritance: When we use inheritance, we should ensure our destructor is virtual to make sure all the respective destructors in the hierarchy are called.
  • Dynamic Memory: If we've used the new keyword to store data, we've got chunks of memory on the heap that need cleaning. Don't forget to release it when the class is destroyed.
Shallow vs Deep Copies
  • Object Copying: An object is automatically copied when passed by value, returned from a function, used as an initialiser or provided to the object's constructor.
  • Copy Constructor: Copies the object using the constructor nomenclature.
  • Assignment Operator: Copies the object when the = (assignment) operator is used.
  • Default: The compiler handily generates these default versions for us and they tend to do a pretty good job of copying objects.
Default Copies
  • Value: The default copy operations simply copies the value of each data member to the new object's data member, known as a 'member-wise copy'.
Heap and Copies
  • Shallow Copy: All the shallow copy does is that it creates another pointer that pointed to the same block of memory on the heap.
  • Deallocation: When one of the objects is destroyed, the block of memory being shared is freed on the heap, leaving the copy with a dangling pointer.
Smart Pointers
  • Smart Pointers: There's a lot of responsibility on the programmer to make sure that memory is released correctly; but to make life easier, smart pointers were invented.
  • C++11: With the recent standard, three new pointer types were added to make working with pointers easier. Auto_ptr is now deprecated as a result.
Unique_Ptr
  • Common Usage: A unique pointer is probably the go-to pointer when using smart pointers.
  • Performance: They are the same size as raw pointers and for most operations they execute the exact same instruction set.
  • Guidance: If a raw pointer is suitable for your program, then it's a reasonable assumption that a unique_ptr also is.
  • Exclusivity: A unique_ptr is exclusive in it's ownership. It always has ownership of the data it points to. Moving from one unique_ptr to another transfers the ownership.
  • Copying: A unique_ptr is exactly that. You don't want two unique_ptr's pointing to the same resource. Hence copying of them is disabled.
  • Why?: When a unique_ptr is destroyed it automatically deletes the memory it points to i.e. dangling pointers.
  • Implicit Conversion: You can't implicitly convert pointers to smart pointers. You need to construct the auto_ptr explicitly.
  • Changing Ownership: We can do this using the reset function on the auto_ptr. Whenever you want to change the smart pointer is managing, use reset.
  • Moving Ownership: We can also change ownership between two unique_ptrs.
Shared_Ptr
  • Dynamic Memory: The lack of garbage collection in C++ is one of the hardest hurdles for new programmers, but shared_ptr allows us the same behaviour.
  • Lifetime: Using shared_ptrs an object's lifetime is managed through shared ownership. No one shared_ptr owns the object.
  • Reference Counted: Instead the shared_ptr tracks all instances that are being managed and only frees the memory when the count is 0.
  • Garbage Collection: Programmers need not worry when the last reference to the memory is destroyed as the object's destruction is now deterministic.
  • Constructors: They simply increase the count and destructors reduce the count.
  • Size: They are twice the size, on pointer for the data and one to keep track of the reference count.
  • Reference Count(1): It's located on the heap, so it comes with all the overheads that allocating on the heap entails.
  • Atomic Reads/Writes: The reference count has to be thread safe. Atomic operations are necessary to keep the threads in sync and are typically slower.
  • Move: When constructing a shared_ptr from another and no longer requiring the original, we should attempt to move rather than copy.
  • Inheritance: Shared pointers also utilise inheritance and have a virtual function (destruction). So there's overhead for memory and cycles here.
  • Reference Count(2): The Reference Count is part of a larger block of memory known as the control block.
  • One Per Shared: For every object that is shared, there is one control block. If an object is shared by five pointers, there's still only one.
  • Contents: 1. The reference count. 2. Custom allocator. 3. Custom deallocator. 4. Other data such as a weak count.
  • Control Blocks: A control block is created when the shared_ptr is created. However, it can't know if one already exists.
  • Make Shared: Std::make_shared will create a new object to point to, so we know it doesn't have a control block.
  • Unique_ptr: When constructing a shared_ptr from a unique one, a control block is always allocated.
  • Raw Pointer: Only use a raw pointer to construct the shared_ptr if you know that it doesn't have a control block i.e. stored as a shared_ptr elsewhere.
Weak_Ptr
  • Weak Pointers: They are pointers that act like shared_ptr's but they do not count towards the ownership of the object.
  • Dereferencing: They can't be dereferenced. Instead you convert them to a shared_ptr before access.
  • Dangling Pointer: It's strength is the ability to check if the object still exists in memory before you can obtain access to it.
  • Atomic Operation: In order for the check to complete and the conversion to a shared_ptr atomic operations are used.
  • Performance: It has the same overheads as the shared_ptr.
  • A Cache: Where we only want read-access but need to guarantee the object still lives.
  • Observer's List: A design pattern that involves other elements (observers) of your software observing the state of specific elements in your game (subjects).
  • Circular Shared_ptrs: When two shared_ptrs point to each other. This forms a deadlock.
After the 'Memory Management' part finished and after the 15 minute break, the next part of the lesson began, which was about Data Structures.

Structs
  • Structure: An array allows you to keep a collection of the same type, where as a struct allows you to combine multiple types in one structure.
  • Grouping: This is useful when we want to group data of different types together, where as an array would not work.
  • Conceptually: The data often stored in a struct is conceptually linked, although not closely enough to be a class.
  • Parameters: Functions with large parameter lists can be altered to use structs which can continue to grow easily.
  • Class-Like: Structs in C++ are actually the equivalent of public classes. Classes are private by default but structs are public.
  • Preference: Prefer classes where it's more than just data that you want to collate i.e. if you want to create member functions etc.
  • Array Support: Because structs have types, they are supported in arrays or container types just like any other.
  • Pointer to Structs: It's legitimate to access the data in a structure using pointers. It follows the same guidance of normal ones.
  • Nested: You can use nest structs within structs if you so choose to do so.
Containers
  • Types: Containers allow us to store objects collectively.
  • Examples: Arrays, Linked Lists, Associative i.e. maps, Unordered, Stacks.
  • Stack: We already know how a stack works, we discussed it when we spoke about memory allocation and the call stack frames.
  • Container Library: C++ provides a container library for these type of implementation, saving you the time and effort.
Vector
  • Arrays(1): Up until now, we've been focusing on C style arrays. Let's look at the container version most used instead.
  • Vectors(1): They are containers that store elements in a contiguous block and can also be dynamically resized during runtime.
  • Internally: They are dynamically allocated arrays under the hood. Their power comes from runtime ability to change size.
  • Reallocation: Once the capacity of the vector is reached, the array will be resized.
  • Why?: Containers offer us more flexibility including iteration.
  • Capacity: The array stored in the vector has a limited capacity. When reached, it's extended.
  • Vectors(2): They are containers that store elements in a contiguous block and can also be dynamically resized during runtime.
  • Allocated Memory: To prevent excessive memory allocations and the cost of moving objects on the heap, the array normally has a reserve capacity.
  • Memory Usage: Memory Usage is higher than necessary because of this. Often the programmer sets a reasonable capacity to begin with.
  • Efficiency: Vectors are fantastic at iterating through objects and at adding new objects to the beginning and the end of the container.
  • Arrays(2): When you need an array, especially one on the heap, then the vector should be your choice.
  • Iterators: Containers use iterators for deciding on how to navigate the array. You can use iterators instead of range based loops; if you want.
With the lectural side of the lesson over, we moved onto the practical side of the lesson. In this practical session, we were given a new project to work on. I didn't managed to get a lot done, ending with copying/moving the lib file from one project's file to another, due to the confusion of where the project needed to be extracted.

Thursday, 15 October 2015

Low-Level Programming_Post4

Low-Level Programming: Post 4 15/10/2015

October 15th 2015 is the date of the fourth lesson on Low-Level Programming.

The lesson that happened on the date above started in a very similar way to last week's lesson, in that, we were given an overview of what we were going to be taught that day. Unlike last week's lesson, however, we went straight into learning the features (last week, we were shown some examples of good/bad Dev Blogs and given an approach on how to work on the DungeonDeath game provided last week).

The following list shows what we were going to be taught today...

  • Memory: Pointers, References, Stacks, Caches, Recursion.
  • Arrays: Multi-Dimensional, Dynamic, Range-Based Loops.
  • Casting: Static, Dynamic and Const (Casting).
Only the Stacks listed above was the only feature taught last week, so I'm going straight into Recursion.
Recursion
  • Recursion: When a function calls itself.
  • Base Case: The first thing a recursive function should do is handled the ending case or cases that terminate the function call.
  • Simplifies: The idea is that for each call to the function we make the problem domain smaller and smaller until it converges on our base case.
  • Invalid Base Case: Make sure your base case will always be reached at some point.
  • Stack Overflow: Every time we call the function a new stack frame is created and items pushed onto the stack.
  • Performance: Can provide succinct solutions to problems but beware of the performance overhead of placing so much strain on the stack.
Cache Coherency
  • Main Memory: Caches are CPU specific areas of memory that are faster to access and write to.
  • Cache Sizes: The CPU often has multiple caches that are slower the larger they get i.e. registers, L1, L2 and L3.
  • Cache Contents: When memory is first read, it's loaded into the cache, these small chunks are known as cache lines.
  • Memory Request: If the memory requested is already in the cache it can be returned, otherwise we have a cache-miss.
  • Multi-Core: Many of today's CPU's have multiple cores, however, we now have the possibility of contention within the CPU cache.
  • Performance: Whilst the on-die caches are still fast, CPUs often share some aspects of their L cache across the cores. This can cause slow-downs.
  • Threads: If multiple threads are pulling in data from different places, but are attempting to use the same cache, we have contention and the other thread has to wait.
Static Arrays
  • Arrays: A collection of items in memory that are of the same type.
  • Management: It's easier to manage a 1000 game objects when they're all stored in a collective.
  • Fixed Size: Static arrays are given a fixed size, denoted by the [] characters and stored on the stack.
Dynamic Arrays
  • Dynamic Arrays: A collection of items in memory that are of the same type and allocated on the heap.
  • Management: We don't have to worry about worst-case scenarios at runtime, we can allocate what we need.
  • No Fixed Size: Dynamic memory allocation for arrays requires a chunk of the heap large enough to store X number of objects.
  • Deallocation: Make sure to deallocate all the memory after we're finished with it.
  • Heap: It's possible to use the Multi-Dimensional nomenclature for arrays allocated in the heap.
  • Access: We now have to do a lot more housekeeping and it takes more effort to pull the data out of the array.
Multi-Dimensional Arrays
  • Collections: Arrays are collections of the same type. The arrays we've been looking at have all been single in their dimensions.
  • Arrays of Arrays: Sometimes we might want to represent a collection as having both rows and columns i.e. a tile map.
  • Conceptual: Multi-Dimensional arrays are purely for the programmer's ease. The compiler remembers the imaginary depth.
Range-Based Loops
  • Concept: You provide a container that C++ can iterate over for you. Leads to cleaner and simpler code.
  • Unsupported: The container has to provide a suitable begin and end function for C++ to utilise range based loops.
  • Const: Where possible we should use a const reference to access the objects (assuming they're bigger than basic types).
Pointers
  • Pointers: Every variable or object we create has a location in our system memory. Pointers hold the addresses of memory locations.
  • Dereferencing(1): If we assign the pointer a type and point it to a valid block of memory where that type is stored, we can dereference it.
  • Invalid Pointers: We know that if we attempt to access an invalid pointer, we get a crash, hence the need for nullptr.
  • Size: A pointer's size is exe and platform independent. The two most common are 32 bit and 64 bit.
  • Type Safe: We can give a pointer a type which enforces type safety, as long as we don't define a void pointer.
  • Dynamic Memory: In order to use dynamic memory we need to use pointers, so we know where to find things on the heap.
  • Dereferencing(2): Defining a pointer to the variable value stores the memory address to the value, causing a level of indirection.
  • Pointer Types: We can store a pointer of any defined type and even no type (void). The various pointer types are 'int *ip', 'double *dp', 'float *fp' and 'char *ch'.
References
  • What Are They?: An alias for an existing variable or object. They allow you to interact and access memory like a pointer.
  • Why?: It's argued that programs are easier to maintain and read through the usage of references.
  • Versus Pointers: You cannot have null references and it must be initialised when it's created. You can't later change what it points to.
  • References Usage: Often used as parameters to a function or as a return value.
  • Pass as Const Reference: Where possible prefer to pass objects by const reference instead of value.
Static_cast
  • Type Safety: C++ is a type safety language, if the compiler completes, it means your programming isn't performing unsafe operations on objects.
  • Casting: Well casting allows us to subvert the type safety net. We can freely use it to force implicit conversions (int to double).
  • C Style Syntax: (T) Expression or T (Expression).
  • Static_cast: Like C cast's this is used to force implicit conversions. It can not cast from const to non-const objects.
  • Usages: Implicit conversion; Upcast and Downcasts of class inheritance; Ptrs to void and void to ptrs; Amongst esoteric others.
  • Code: It's clear than traditional casting, we can just search for static_cast and we know that a cast is being performed.
Dynamic_cast
  • Safe Polymorphic Casting: You can cast a pointer or reference to any polymorphic type supported class. That can be up or down or even sideways through the inheritance chain.
  • Result: The resultant object will guarantee successful casting. If it has failed the pointer, it returns will be null or std::bad_cast if a reference.
  • Limitations: Diamond inheritance must utilize virtual. Protected/Private inheritance will fail.
  • Performance (RTTI): Depending on the compiler's implementation of the dynamic_cast, there can be considerable slowdown.
Const_cast
  • Constness: It's possible to remove an object's constness. This can be achieved through the usage of const_cast.
  • Responsibility: You're telling the compiler that this variable or object should be mutable, that you know best.
  • Guidance: Don't do it unless absolutely necessary. If you can't code the correct const solution or make changes to the code base.
  • Ramifications:  By breaking the constness of the object, users of the code calling what they believe to be const functions could end up with changed data.
After the lectural side of the lesson, we continued to work on the DungeonDeath game that was provided to us last week. In the lesson, I attempted to add a exit game option and to add more levels to the game. I managed to add the exit game option to the game, but when the program breaks, it still leaves the default comment when we don't decide to go north or south. Near the end of the lesson, we started on making the extra levels/rooms, since there were only north and south rooms programed into the game. I managed to create a startup room for the east side, but I then ran out of time to continue.

Thursday, 8 October 2015

Low-Level Programming_Post3

Low-Level Programming: Post 3 08/10/2015


8th October 2015 is the date of the third lesson on Low-Level Programming.

Unlike the previous lesson that I had, in which the beginning was a recap of what we were taught in the first lesson, the lesson today was a cover of what we were going to be taught today, before the practical side of the lesson, which is in the last hour of the lesson. But before I get to what we were taught today, there were two different features that were shown to us. Both of these were to help us to develop the 'Dev Blogs' and a way to approach the Dungeon Game code provided to us last week.

The first of the two features that was mentioned in the above paragraph was that we were provided with some examples on how to develop the Dev blogs. Some of the examples were good, others were bad.

Despite there being only 1 image on the good side of how to develop the Dev blog, it is/was helpful nevertheless. The image provided what was taught in the lesson, the key points/concepts from the lesson and a personal point of view on how the person who wrote the post felt about what was taught in the lesson. The last point about the person saying their view about the lesson surprised me a little, but I completely understand why he/she provided their personal opinion on the lesson.

There were, however, 3 images that showed how the Dev blogs shouldn't be done. The three examples ranged from saying the computers were 'crap' and not understanding as to why we had to fix some compiler errors, only mentioning some of the main points taught in the lesson and, my personal 'favourite', a post that only had the words "Write blog entry here". These posts also helped me despite being completely rubbish, as it gave us examples on how NOT to do Dev blog posts.

The second of the two features that was mentioned in the paragraph was that we were given a method on how to approach the coding task from last week, in that, some images were provided on listing the various variables, states and so on that are listed on each different object. For example, the first image showed that the 'bat' object contains the following: Attacks, Defends, Is It Alive?, Renders, States and two mini variables connected to the States, which are Has Health and Has Damage Modifier. The player, though sharing some of the characteristics of the bat (enemy), it also has some differences. The 'player' object contains the following: Defends, Attacks, Has Score, Has Health, States and three mini variables connected to the States, which are Has Score, Has Health and Has Damage Modifier. It also showed some OOP graphs on the different variables mentioned in the bat and player object(s).

For example, the bat's graph is as follows...


The player's graph is as follows...

The GameObject's graph is as follows...

After the two parts of the lesson (Dev blogs and 'How to approach the code from last week') and after the break, we were taught some new features and a small recap, since I knew some of the features from last year. Some of them include Memory Allocation, both static and dynamic, stacks, scopes and nullPtr.

Static Memory Allocation
  • Default Behaviour: When we create instances of object memory is automatically allocated on the stack.
  • Lifetime(1): The memory remains allocated until the object or variable falls out of scope.
  • Cleanup: The memory cleanup process is automatic.
  • Lifetime(2): All objects, variables and arrays have a known size throughout the programs run.
  • Management: Removed from the programmer's concern.
Scopes
  • Scopes: Areas in our code where we combine functionality.
  • Organisation: Everything in our program can be seen as organized into these scopes i.e. functions, classes etc.
  • Memory Allocation: When the scope terminates, all the memory that's been statically allocated get's released.
  • Variables: Anything destroyed in this scope won't be accessible. This is why we shouldn't return references or pointers to objects whose lifespan ends when the function does.
Stack
  • Stack: A fast and organized dedicated area in memory. where we store instances of variables and objects at runtime.
  • FILO: First in, last out principal. We push and pop items off the stack.
  • Memory: Memory is managed for you.
  • Static: Everything needs to be a known quantity at program run.
  • Size Limits: It's a limited amount of memory and it's possible to utilise it all. Stack Overflow is 'Game Over'.
  • Local Storage: When the function call ends, all data is popped off of the stack.
Dynamic Memory Allocation
  • Dynamic Memory: The opposite if Static memory. The complier is unable to determine the amount of memory it needs to allocate.
  • Lifespan: Dynamically allocated memory lives independently of the function it's allocated in.
  • Allocation: The programmer is in charge of both allocation and deallocation.
  • Heap: Instead of the stack, dynamic allocation occurs on the heap.
Heap
  • Heap: A region of memory that's not automagically handled for you.
  • Organisation: Unlike the stack, it has no defined structure, you can add and delete memory as you see fit.
  • Allocation: In order to allocate memory dynamically, we use the new keyword.
  • Access: In order to access the memory, we now need to deference a pointer,
Automatic/Dynamic
  • Memory Usage: Dynamic allocation allows us to reserve only the amount of memory we require i.e. less wasted unused portions.
  • Speed: The stack is faster to access than the heap due to the level of indirection a pointer deference incurs.
  • Memory Management: Stack usage means the memory is freed when it's not needed, unlike dynamic. You can't 'leak' the stack.
  • Memory Organisation: The stack is organised in such as way that memory fragmentation will not occur. The heap offers no such assurances.
  • Memory Limits: The stack has a memory limit, the heap does not. However, the hardware has a finite amount of memory before swapping happens.
  • Resizing of Memory: It's actually possible to take an item in the heap and dynamically resize it.
NullPtr
  • Null Pointer: The null pointer is a non-valid pointer i.e. it doesn't point to any memory location.
  • Usage: Using the null pointer we can run checks before we try and deference it. This will save us crashing if it doesn't point anywhere.
  • Deletion: When we free some memory from the heap, we should always make the pointer null.

Saturday, 3 October 2015

Low-Level Programming_Post2

Low-Level Programming: Post 2 01/10/2015

1st October 2015 is the date of the second lesson on Low-Level Programming.

The start of the lesson was essentially a recap of some of the features learnt from the first lesson. I have already gone into some detail about some of the features learnt from the first lesson on my first post. The next paragraph will show what else was taught in the lesson, from Static Member Variables, Public/Private Inheritance, going into detail on Constructors and so on. The first part explains about Static Member Variables, with some of the following notes used from the lessons mixed together.
  • Static Member Variables force a single shared instance amongst all objects instantiated of that class.
  • They belong to the class itself and are shared amongst instances.
  • As they are treated independently of class instancing they must be explicitly defined to a non-zero value (where a non-zero value is desirable) outside of the class definition.
  • To access them we use the scope operator '::'.
  • The static variable resides in the class scope but does not belong to objects of that class. It belongs to the class.
  • Class definitions are often included in multiple translation units i.e. CPP. The static variable should be shared amongst all and not stored as copies.
  • As it resides within the class scope (similar to namespace) we access it using the :: operator. We can access it through instances of that class, but it then becomes unclear that it's static access.
  • Static values are stored in the data segment which is a portion of the object file or the virtual address space of a program that contains variables. Const statics are stored in the rodata segment.
The next paragraph is about Public/Private Inheritance. The following info was found on a website about Inheritance.

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the baseclass, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Public Inheritance: When deriving a base class from a public base class, public members of that base class become public members of the derived class and protected members of that base class become protected members of the derived class. A base class's private members are never accessible through calls to the public and protected members of the base class.

Private Inheritance: When deriving from a private base class, public and protected members of the base class become private members of the derived class.

The following line(s) is some more information based on Constructors.


Initialisation

  • Member Variables need some 'Sane' values. (int maxBoost = 50).
  • Use Initialiser lists and not the body of the constructor.
Viral Functions
  • Don't call virtual functions from constructors or destructors. They don't exist.
  • The most derived function will never get called, as that part of the class doesn't exist yet.
  • As construction happens at the lowest level first, the derived member variables won't have been initialised.
  • Compliers may warn.
  • The program may compile but not link.
  • If it makes it to runtime, it'll either crash or perform unintended behaviour.
The next part of this page are some of the new features that we learnt from the lesson.

Default and Delete
  • If we don't define default constructors and assignment operators the complier will do this for us.
  • We can use the default keyword to acknowledge we intend for the compliers default version to be used.
  • Use 'Delete' when we don't want to allow usage of functions.
Delete
  • Traditionally we use private non-defined functions.
  • We can use delete to invalidate the function call both to automatically constructed functions and ones of our choosing.
  • Will also use template instantiations.
After the lectural side of the lesson, we moved onto the practical side of it. The exercise given to use was to work on the DungeonGame from the last lesson and refactor the code using OOP and how we would handle the animations per object. We quickly split the various components into categories, such as the bat having a render, the 'Newton's Cradle' having an animation (as if the game was loading) and the player itself. The Newton's Cradle and the Bat were put into the Redner category as they both get displayed after some time when the program runs, but an Animation feature was added into the Newton's Cradle object as it was the only object in the game to have an animation. The player and the bat shared the health and attack functions, however, and so were linked together as a result. Sadly, we ran out of time to finish the task(s) and couldn't continue further.