Skip to main content
IMG_20150706_114553920

Weekly log #3 – Accelerated C++ finished!

This post is actually from the previous 2 weeks.

I finished the book Accelerated C++, by Andrew Koenig and Barabara E. Moo, and started the book Game Engine Architecture by Jason Gregory. Thus, this post is the last highlights through the Accelerate C++.

C++

Assignment conversion

When using the assignment operator (=), the compiler may use constructors with single arguments to implicit convert the right value of the expression. For instance:

The assignment creates a temporary object string that receives “this is a char*” as parameter and copy all the temporary object attributes to the s object.

Friend functions

Inside a class, you can define external functions that are friends, for example:

This means that the function “externalFunction” can access the private properties of MyClass.

Class protection

  • Public methods can be accessed by all objects.
  • Protected methods can only be accessed by children of the class.
  • Private methods can only be accessed by the class that defines it.

Notice that this is different from Java, in which protected methods means that only objects in the same package can access that information.

Inheritance visibility

Inheritance in c++ also has visibility access:

  • In public inheritance, everything is aware of the inheritance.
  • In protected, the child and subsequent children are aware of the inheritance.
  • In private, only the immediate child is aware of the inheritance.

See http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance.

Virtual functions

Suppose you have two classes:

and the function:

Normally, we would expect to be print “1” and “2”, but in both cases the result is “1”. That is because you must explicit say to c++ when you want to use the children methods in polymorphism. You do that with virtual functions:

With this, now we have “1” and “2”.

Note: the polymorphism is only possible when working with references or pointers.

Virtual destructors

This is really, really ugly.

The same example about virtual methods above is also valid for destructors. If you call the destructor of d, without virtual, the Child destructor won’t be called and this will probably send your program to hell. Always declare destructor as virtual if you want to use inheritance.

Pure virtual methods

When you do:

You are declaring m as a pure virtual. This means:

  • The method m is abstract and MUST be overridden by children.
  • The class is abstract and CAN’T be instantiated.

Forward declarations

Used when you need to use a name before defining them. For example:

Storage-class specifiers

Determine location and lifetime of a variable:

  • register: suggests that the compiler should try to put the variable into a register (in order to optimize the access);
  • static: preserves a variable after leaving the scope;
  • extern: tells the compiler that this is not a definition, only a declaration. The variable is defined somewhere else;
  • mutable: allows a variable to be changed even when an object is const.

IMG_20150706_114553920
How the book looks like after all annotations
TheLastofUsPoster

Weekly Log #2 – C++, E3 and The Last of Us

This was a long week. We had E3 conferences starting Sunday night (for Brazil) and ending on Tuesday, with a lot of awesome – official – announcements: Fallout 4 (my next love), Dishonored 2, Doom 4 and new IPs such as Horizon (which looks very promising), unravel and others. During the week I’ve been playing Fallout shelter also announced on E3, which is a good-looking and funny mobile game, but has the same problems of other farming games: there is no end and it gets bored fast.

In the weekend, I start-and-finished The Last of Us. Man! What a game! I love post-apocalyptic games with adult narrative. My only regret is that I didn’t gave more time to it – I had to play on easy in order to finish in this weekend because I won’t be able to play it for the next week, and if I have more than 1 week gap between my gaming sections, I just can’t continue from where I stopped.

C++

Even with all stuff that happened this week, I almost finished the Accelerated C++ book. Here are some highlights:

Maps

You can create ordered maps defined in <map> and unordered maps defined in <unordered_map>. Their usage is similar, but map is slower to add new items due to the ordering function. Usage:

If you try to access a nonexistent key in the map, this key will be created automatically.

Maps return pair objects as iterators. A pair type is defined as pair<const K, V> and has the following attributes (to key and value, respectively):

About double angle brackets

In cases like map<string, vector<int>>, the compiler may have problem to parse the statement (due to the >> symbol), so it is recommended to use map<string, vector<int> > (with the space). This seems to be a an old practice, I doubt that compilers nowadays still have such problems.

Default arguments

You can use default arguments on function parameters, like Python:

Notice that, the parameters with default arguments must be the last items on the list.

Constant methods

C++ has a mechanism to protect object from write access, for example when you define a function like:

where non_writable is constant. When a parameter is defined as constant, C++ only allows to read public attributes and call const methods, such as:

Brackets on const maps

Due to the constant restriction described above, constant maps don’t have the operator [ ], because this operator changes the map when the key doesn’t exist.

Generics/Templates

Generics are called templates in C++ and is used as:

With stand-alone functions you don’t have to specify the template explicitly, e.g.:

The typename keyword

C++ has so many features on it that sometimes the compiler simply doesn’t know what to do. For instance, when you try to define a variable within a subtype defined inside a template, like this:

In this case, the compiler interprets SubType as a static member of T, thus, it tries to multiply SubType with ptr, causing an runtime error. Because of this, you always must use the typename keyword, avoiding compiler mis-interpretation:

Reference: http://stackoverflow.com/questions/1600936/officially-what-is-typename-for

Iterator categories

There are 5 types of iterators. They are divided by what they can do (thus, which operators are allowed) with the object they reference. The categories are:

  • Input
  • Output
  • Forward
  • Bidirectional
  • Random access

Consult http://www.cplusplus.com/reference/iterator/ to see the table of all operations these iterators handle

Stream iterators

istream and ostream can be used as iterators:

This piece of code sends all elements of a vector v to the console output.

Default constructor

To avoid double initialization when you create an object, you must use the constructor initializers:

Without this, C++ initializes the object attributes before the constructor body, and in constructor you probably will initialize the attributes again.

Pointers

Just a reminder:

  • &x returns the address of the object x
  • *x returns the object in the address x

Pointers to functions

You can create pointers to functions as:

This creates a pointer fp of a function that receives and return int values. Notice that you don’t have to use &my_function, because C++ convert functions automatically. The same can be applied to the usage (you don’t have to call (*fp)(2), only fp(3)).

You can also return a pointer to function from another function, this is a bit tricky because you have to use typedef to declare the pointer before:

To return a pointer to a function that uses template is trickier, you will have to define a struct with the pointer and return the struct.

Arrays

C++ arrays are pointers to values and, thus, they can be used as iterators:

Notice that, the variable array stores only the first pointer, thus *a == 2.

The index usage array[3] is equivalent to say *(array+3).

Because array is only a bunch of pointers, you don’t have the type_size directly, but you can use size_t from <cstddef>.

File streams

Using input or output files is pretty easy:

The usage is the same as cin and cout.

Specific streams

Instead of cout, you can use cerr for error output (it is preemptive, so it prints the string when it is called), and clog for logging (non-preemptive).

New and delete

To allocate and deallocate objects manually, use new and delete:

If you allocate an object manually, it will only be deallocate manually too. You must be very careful to avoid memory problems!

Explicit constructors

C++ allow explicit and implicit object initialization:

The explicit keyword prevents the compiler to use the wrong constructor due to wrong type conversions:

This

Another reminder: this is a pointer to the object.

Copy constructor

Passing an object by value to a function, returning an object by value from a function, or simply assigning one object to another variable, implicitly copies the object. The constructor used in the case is called copy constructor:

Rule of the three

To control all creation and deletion process of a class, you must implement at least the following methods:

Citing the book:

Because copy constructor, destructor, and assignment operator are so tightly coupled, the relationship among them has become known as the rule of three: If your class needs a destructor, it probably needs a copy constructor and an assignment operator too.

ShowCover

Weekly Log #1 – Motivation and C++

I started this blog intended to post my developments and things that I’ve been learning during my path towards game industry. But, in general, I’ve only been writing tutorials and releases notes. Tutorials are pretty hard to do, because I like to create examples, format, make images, revise, and give details about what I’m writing about, and releases notes are only published when I have a release to announce. Both demand time, which I don’t have much lately. In consequence, my posts now have about 1-month gaps among them, and this isn’t good.

Thus, in order to keep my initial plan and write more frequently, I’m creating a weekly log, starting with this one, so I can register and tell what I’m studying or developing.

C++

In this post I will only talk about C++, which I’ve been studying almost exclusively.

First thing to say is, I’m following the book Accelerated C++ by Andrew Koenig and Barbara Moo. The book is pretty good, but I wouldn’t recommend for a total beginner. In my opinion you should learn the basic on other languages before getting this book – and language.

I am learning C++ in depth because I want to have some experience on the AAA industry, so this is pretty much obligatory. I understand that C++ is a pretty powerful language, but damn, this language is complex as hell. Notice that I’m not talking about syntax or readability, I’m talking about the concepts behind every feature of C++. There is a lot of redundancy (you can solve problems in a dozen of different ways) which seems to be caused by the performance concern (generally there is a super – but complex – parsimonious solution).

During the course of this book (and the followings) I will share more my thought about the language. For now, I’m going to give some highlights of interesting stuff on the book:

Abstraction

The author’s give a pretty good definition of abstraction right on preface:

We define abstraction as selective ignorance – concentrating on the ideas that are relevant to the task at hand, and ignoring everything else

Containers and size_type

Most STL containers provide a size_type type, which defines the appropriate type to hold the number of elements of a given container. For example, to move through a string, you should use:

instead of:

The reasons of that is because the number of elements in the container may be bigger than what int (or unsigned int, etc..) can handle.

The & operator

The & denotes a reference to some variable.

As a good practice, you should use const to tell programmer when your function does not have intention to change the parameter value. E.g.:

The istream objects

istreams have a failure state that is kept until cleared, thus, if you put a string on to this:

you won’t be able to read anything until you clear the stream:

lvalue

Non-const arguments can only receive lvalues  (can’t be anonymous):

The same is valid for return values.

Header files

You must avoid the use of using inside the header files, because your never know how the source file will use the variables. Avoiding using you avoid unnecessary conflicts.

Also, you must always use the preprocessor directives:

because compiler insert the header code into the source files that import the header. Without it, the definitions would repeat several times causing errors.

Inline functions

Inlines functions are cool, they only exists before compiling. The compiler copy the body of the inline function where it is called. Use this to avoid the overhead by function calls.

Built-in exceptions

Import <stdexcept> to use the default error classes:

  • logic_error
  • domain_error
  • invalid_argument
  • length_error
  • out_of_range
  • runtime_error
  • range_error
  • overflow_error
  • underflow_error

using:

Vector limitations

Vectors are optimized for random access and pushing/removing items from the beginning or end. Other operations are slow. The reasons for that is that vector move all elements back or forward when you change items at middle of the container.

Note: for fast insertions or removing, use list. However, list items can only be accessed sequentially.

Iterators

Iterators are cool, and in general are implemented as pointers (but not true all the time). You can use the following iterators:

each one for a specific situation: const to handle const values, reverse to reversed loops, iterator for common loops. For instance, to move through a string you can do:

Overloaded function as arguments

You must avoid using overloaded function as arguments to functions, because the compiler can have problems to decide which function to use. Instead you should use an auxiliary function.

Static variables

You can use static storage class specifier on local variables inside functions. A static variable is created the first time the function is called and reused in subsequent calls.

Using functions as arguments

To create functions that receive other functions as parameters:


A final note: the STL has A LOT of interesting things, for instance, check the algorithm package.