I have recently come along a struct of this sort:

struct Context
{
  Context(): addTitle(false) { }

  bool addTitle;
  std::string title;
};

It looked strange, especially the Context(): addTitle(false) { } part.
Can anyone please explain it for me.

This is a piece of C++ code. This code defines a new type; the type is a struct, named Context.

The code then defines the default constructor Context() for this new struct. You do not have to define a default constructor for a class or struct; if you do not, the compiler will create one for you. If you want to ensure something is done on construction of an instance of the struct (or class), you can do it with a default constructor. In this case, the coder wants the variable addTitle to start with a value of false.

In that default constructor, the member variable addtitle is set to false using an initialiser list, which is the addTitle(false) part. The empty braces { } are there because this is defining a function. The function doesn't have any code in the braces, but it's still a function.

So, if you were to now make an object of this type

Context anInstance;

you would find that anInstance.addTitle is set to false.

Very well explained, thank you. I just want to get further clarifications; so constructors exists in structs like in classes? Does this also happen in C structs?

In C++, a struct and a class are identical but for default accessibility (i.e. public or private) and a similar difference for inheritance.

In C, structs do not have constructors or any other member functions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.