Cogito Learning » 2015 » February Professional IT Courses Wed, 02 Dec 2015 11:11:23 +0000 en-US hourly 1 Four things you probably didn’t know about C++ Thu, 26 Feb 2015 12:27:52 +0000 Read more]]> Today I want to share a few “features” of C++ that you probably weren’t aware of. I placed the word features in quotes because most of them are confusing and there are only a few cases where they miht be useful. In many cases thrying to use these oddities will result in bad or at least unreadable code.

Case label placement

Did you know that case labels in C++ resemble the labels used by our old foe, the goto statement? We all know that goto is evil but it is still part of C++ language. Even modern compilers will compile the following code without any problems.

void badFunc() {
    if (i>5) goto aargh;
  std::cout << "Aargh!" << std::endl;

See how we have defined a label called aargh. Inside the loop we transfer program execution to the code following that label using the goto aargh statement. Also notice how the colon : resembles the colon used in the case labels of a switch statement. The reason for this is that internally the compiler produces very similar code.

switch (number) {
  case 0: 
  case 1:
  case 2:

We usually indent the case labels to make them look less like the old goto labels. In many situations the compiler treats them more or less the same. A standard way for the compiler to implement the switch statement is to use a jump table. The argument of the switch statement is used to look up the position of the corresponting case label. Much like goto, code execution is simply transferred to that point. This is also one reason why you need break statement if you only want part of the code after the label to execute.

One consequence of the way C++ understands case labels is that they can appear at any level within the switch statement. I have contrived this horrendous example which compiles and runs perfectly well in any modern C++ compiler.

#include <iostream>

void reallyBadCode() {
  int option;
  std::cin >> option;
  int N = 10;
  int i = 3;
  switch (option) {
    case 0:
      N = 5;
    case 1:
    case 2:
      std::cout << "Loop not executed" << std::endl;

See if you can figure out what the code does before trying it out.

One real life example of the use of this language feature is Duff’s Device.

And one more little fact about labels. Did you know that you can place an arbitrary URL into your source code.

The protocol name including the colon define a label called http. What follows is a double slash so the remainder of the URL is treated as a comment.

Assigning to ternary statement

Now we probably all know the ternary statement condition?ifTrue:ifFalse and we regularly use it to assign values based on some condition.

a = (c=='y'?-1:1);

But did you know that ternary statements can evaluate to an lvalue. If you don’t remember what an lvalue is, it is a value that you can assign a value to. Or in other words a value that can be placed left of the assignment operator. Consider the following example.

void ternary_assign() {
  int option;
  std::cin >> option;
  int a = 0;
  int b = 0;
  (option>1?a:b) = 1;
  std::cout << "Values of a and b: " << a << " " << b << std::endl;

Here the value of the option variable determines which variable we assign to. If option is greater than 1, we assign a value to a and otherwise to b. But this is not the end of it. You can also use it select an object and call a method on that object.

class Person {
    std::string name_;
    Person(std::string name) : name_(name) {}
    void printName() {
      std::cout << "My name is " << name_ << std::endl;

void ternary_object_selection() {
  int option;
  std::cin >> option;
  Person a("Alice");
  Person b("Bob");

And finally remember that function names in C++ can be used as function pointers. These are pointers to the memory address where the compiled code of the function body is stored. Useing the ternary statement we can select a function pointer and call the function associated with it. Here is an example.

void ternary_function() {
  double x;
  std::cin >> x;
  double result = (x>0.0?sin:cos)(x);
  std::cout << "Result is " << result << std::endl;

Note that we are not calling the sin or cos function inside the ternary statement but the ternary statement evaluates to a function pointer. Only after that has been evaluated the function is actually called.

The array operator is associative.

You know that one of the features of C and C++ is pointer arithmetic. Some love it and some hate it. But did you know that behind the scenes both languages use pointer arithmetic all the time. Remember that C style arrays can used like pointers, and also the other way around. In fact C++ makes almost no distinction between the two. You might have already geussed it, when you access an element from a plain array C++ uses pointer arithmetic to retrieve the element. The expression arr[3] is synonymous to *(arr+3). Here arr is treated as a pointer. We add three to the pointer and dereference to get the third element. But instead of *(arr+3) we can also write *(3+arr), right? This leads us to suspect that you might be able to write 3[arr] and, indeed, you can.

Here is a piece of code for you to try out.

void array_assoc()
  double values[5] = {0.0, 1.0, 3.14159, 1.41421, 1.61803};
  double x = 2[values];
  std::cout << "The value is " << x << std::endl;

Of course the array index does not have to be a literal but can be any integer expression.

void array_assoc()
  int n;
  std::cin >> n;
  double x = ((n>0?n:-n) % 4)[values + 1];

For good measure I have added used some obvious pointer arithmetic inside the square brackets. This is of course allowed.

Pure virtual functions with function body

Now we are coming to a feature that has a more C++ feel to it, pure virtual functions. You learn about pure virtuals in the context of defining interfaces and many textbooks claim that you can’t instantiate an object containing a pure virtual because the function doesn’t have a function body and the compiler wouldn’t know what to call. That is not completely correct. True, you can’t instantiate an object with a pure virtual. Nonetheless, the pure virtual can be implemented and also called from derived classes.

Here is a full working example.

#include <iostream>

class Base {
    virtual void doSomething() = 0;
    virtual ~Base() {}

class Derived : public Base {
    void doSomething();

void Base::doSomething() {

void Derived::doSomething() {

int main() {
  Derived d;
  return 0;

In contrast to the previous examples, this feature can actually be useful in some contexts. From Scott Meyers book “Effective C++”:
Derived classes that implement this pure virtual function may call this implementation somewhere in their code. If part of the code of two different derived classes is similar then it makes sense to move it up in the hierarchy, even if the function should be pure virtual.

]]> 4
Android Custom Views: The onDraw Method Thu, 19 Feb 2015 08:46:03 +0000 Read more]]> When you create you own custom view you will probably give the view its own special appearance. You probably want to draw the elements of the view onto the screen somehow. This is achieved by overriding the onDraw method of the View class. The signature of this method is

protected void onDraw (Canvas canvas);

When you implement the method you are given a Canvas object on which you can draw you view. This method will be called when the system decides that your view should be rendered onto the screen. The following implementation of the onDraw method will draw a red circle that is centered in the view and almost filles the area occupied by the view, leaving a margin of 10 pixels.

public class ColorPicker extends View {
  Paint paint = new Paint();

  // ...
  // constructors see previous tutorial
  protected void onDraw (Canvas canvas) {
    int w = getWidth();
    int h = getHeight();
    int radius = Math.min(w,h)/2 - 10;
    paint.setARGB(255, 255, 0, 0);
    canvas.drawCircle(w/2, h/2, radius, paint);

The combination of a Paint object with the Canvas is a powerful tool for creating complex drawings. More on these two classes will be presented in future tutorials.

In essence, this is enough you need to know about the onDraw method if you want to implement a simple View. However there are some details that you should be aware about if you intend to write a usable View that behaves well.


One thing you might have noted is that the Paint object is created as a class member of our ColorPicker class rather than as a local variable inside the onDraw method. This is done for performance reasons. The onDraw method is called from the UI thread. This means that you should make sure that the code inside the method performs as fast as possible. Anything that takes too much time should either be done during initialisation or in a separate thread. Allocating objects with new is can be quite a performance drag, especially if done repeatedly. For this reason you should avoid allocating new objects within the onDraw method.

If your drawing becomes elaborate and requires some time consuming computation you should consider placing the code in a separate thread. This will take load off the UI thread and make your view more responsive. One class that is very useful in this context is the Picture class. I will be talking about drawing into a Picture in a future tutorial.

Getting the dimensions

One thing you will need to do when drawing your view onto the canvas is to find out how much space you have for your view. You might be tempted to look at the Canvas reference and you will find that Canvas provides two methods getWidth and getHeight. However, the Canvas dimensions are not reliable in telling you the size of your view. Instead you should use the getWidth and getHeight of the View itself.

If you search the internet for ways to find the width and height of a custom view you will come across a common solution that overrides the onSizeChanged method. This solution might lead to slight performance increase but is not really necessary if you draw your view completely from the main thread. A future tutorial will go into the details of how to use the onSizeChanged method. For simple views, you can call getWidth and getHeight from within the onDraw method.

Do I need to call super.onDraw()?

This is a question that arises when beginners start to implement their own onDraw method. It might seem logical that View.onDraw is responsible for drawing the background of the view. This is not the case. In fact, View.onDraw has an empty implementation and calling it won’t make any difference to how your view appears. For sake of brevity I usually omit the call to super.onDraw.

When is onDraw called

The onDraw method is called whenever android thinks that your view should be redrawn. This can be tha case when your view is animated, in which case onDraw is called for every frame in the animation. It is also called when the layout changes and your view is re-positioned on the screen.

But what if some data inside your view has changed and you want to make sure that the view is redrawn. You can’t call onDraw directly. Instead you should call invalidate to tell the view that it needs to redraw itself.

]]> 0


The basic class API


class PricingEngine : public Observable {
    class arguments;
    class results;
    virtual ~PricingEngine() {}
    virtual arguments* getArguments() const = 0;
    virtual const results* getResults() const = 0;
    virtual void reset() = 0;
    virtual void calculate() const = 0;




class PricingEngine::arguments {
    virtual ~arguments() {}
    virtual void validate() const = 0;

class PricingEngine::results {
    virtual ~results() {}
    virtual void reset() = 0;


The Generic Engine


template<class ArgumentsType, class ResultsType>
class GenericEngine : public PricingEngine,
                      public Observer {
    void reset() { results_.reset(); }
    void update() { notifyObservers(); }
    mutable ArgumentsType arguments_;
    mutable ResultsType results_;




]]> 3