Monthly Archives: May 2016

Introduction to structs

In D, like in all modern languages, you can define your own types.

These are the four custom types of… types you can create:

  • struct
  • class
  • union
  • enum

This tutorial is an introduction to structs.

structs are types that are defined by programmers and represent records. For example, you could have a Point struct that has two data members: x and y.

Let’s see a simple example.
Suppose we are making an application with jokes.
We could define a type, Joke, to hold the required data of a joke:

Alright, seems easy. But a jokes application without jokes sucks… So let’s add some!

Note that we are able to construct the jokes with the syntax: Joke(id, text, category).

Better. The users might actually laugh now.
But there’s still a small problem. The data members are public, which means a reckless programmer might accidentally mutate them. We don’t want this to ever happen, so let’s define some getters.

What we have done is to make id, text and category const private member variables, and provided property getters to access them.

We could have made the variables const without providing property getters, but as good citizens of encapsulation, we should not expose the public fields.

Here is the full source code:

And the output:

Category: Chuck Norris
“Some magicians can walk on water. Chuck Norris can swim through land.”

Category: Food
“Why don’t the French eat snails? They don’t like fast food.”

Category: Animals
“Why did the dinosaur cross the road? Chickens hadn’t evolved yet”

Want more? Check out Humorista: https://play.google.com/store/apps/details?id=greenbits.humorista

Fun with implicit conversions

What does this print?

Without much thought, you’d answer:
A
B

But you would be wrong! This program actually prints lots of “As” until the stack overflows and the program crashes!

Why?

A simple fix is to declare the two functions before defining them, so the second foo with be visible inside the first one.

The real question though, it why the string was being converted to an optional<string> in the first place.

Let’s examine the header file of boost::optional.

Aha! The constructors are defined as follows:

As you can see, the constructors are not marked explicit . What this means is that a value of type T can be implicitly converted to boost::optional<T>, which is exactly what happened in our case.

Implicit conversions are bad (most of the time) when constructors accept exactly one argument.
This seems to be one of those times.
Why the designer of boost::optional decided not to mark the constructors as explicit is beyond me.