Gentle Introduction to Boost Phoenix

Motivation

Boost Phoenix is a library for functional programming in C++. To understand Boost Phoenix we need to understand what functional programming is. In next part we will go through little bit of introduction with functional programming. Then we will proceed with boost Phoenix.

Functional Programming & Phoenix

I love Wikipedia so we will quote it out here

In computer science, functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) each time. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.

For some time functional programming has only been the tool of academia and research. But recently there has been a revamp with people adopting them for general purpose use. Some of the most complex systems with the most rigid requirements are written using functional programming elements. In general functional programming has its root in Lambda calculus, which is the mathematical tool which tells us how to construct terms from terms. In simpler terms it is the theory of creating functions from functions. We have small functions, we construct larger and more complex functions from them. Stricter functional programming languages are typically used when a system’s performance and integrity are both critical. The real benefit of adopting a functional style is that our programs can be broken down into smaller, simpler pieces that are both more reliable and easier to understand. As described by Wikipedia the states in functional programming are immutable. So we can only construct new states, we cannot change them. This makes it easy to optimize and reason about the program. It also lets us lets us write powerful constructs using smaller atomic constructs.

I will not write more about functional programming here, there are already a lot of articles. Links are given in the end of article.

Boost phoenix is a library which helps us write functional programs in C++. As we will see in certain cases it makes the constructs compact and less cumbersome. The Phoenix library enables functional programming techniques such as higher order functions, lambda (unnamed functions), currying (partial function application) and lazy evaluation in C++. The focus is more on usefulness and practicality than purity, elegance and strict adherence to functional programming principles.

Reference

Compiler Construction – Implementing my own toy language in C++ – The Language Odra

In this section we will not down the features of Odra.

Language Goals

  • Simple syntax
  • Expressive but keep typing to minimal
  • Embeddable
  • Can be used in game scripting
  • Simple to write a compiler/interpreter
  • Easy to learn, should not differ significantly from C++ or Java or JavaScript
  • Easy to integrate with C++

 Language

The language will be represented with ASCII.

Odra will be a general programming language with game scripting in mind.

Odra will have static as well as dynamic typing. Making it good for static types and also making prototype based programming easy. This will help users to write prototypes quick but will also let them write typed programs which are better, safer but with minimal modification.

Basic Data Types

bool boolean true or false
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers

byte alias for uint8

any can hold any type. It is used for dynamic typing.

array is a numbered sequence of elements of a single type, called the element type. Length can be found from array.length

string is a series of character. The length of string can be found from the property string.length

struct is a sequence of named elements, called fields, each of which has a name and a type.
// This is comment
/*This is comment too*/
var a, b int
var c any

<Prev  TOC  Next>

Compiler Construction – Implementing my own toy language in C++ – Introduction

 Table of Content

  1. Introduction
  2. The Language Odra
  3. Implementing the Parser
  4. Source Code

Introduction

Long back I wrote some articles on basics of compilers. Here is the link. After that other priorities took over and I didn’t do much learning on this subject. Recently I have started learning again. In these series of articles I will try to build a small compiler. We will be using some standard tools for this subject. We will use Boost spirit framework and llvm frame work for our task. I do not intend for these articles to be basic articles and I will avoid most of the lengthy theories here. There are a ton of resources out there in net that deals with them. Rather I will keep the articles as a well commented developer design note, where I will talk about the implementation details, the problems I faced and also the solution I choose.

Choosing the Toy Language

For the language I have the choice of COOL (Classroom Object Oriented Language) or AngleScript or Go. COOL is used in the stanford compiler design course and AngleScript is a small scripting language for games that is used for game scripting.

COOL

Cool is a small language designed for use in an undergraduate compiler course project. While small enough for a one term project, Cool still has many of the features of modern programming languages, including objects, automatic memory management, and strong static typing. Although it has all the high level features of a good language, it has less syntactic sugars that may hamper learning. First lets have a look at some of the important features of COOL.

Cool is a statically typed object oriented language. All the COOL code is organized into classes. Each class should be in a single source file. COOL class can have attribute members and methods. In cool the object hiding is very simple. All the member attributes have private scope and all the methods have public scope. There are no private methods or any public attributes.

Ex:

class  [Name] inherits [Type] {
 Methods and attributes.
};

In COOL all class name is also a type. We also see that COOL supports inheritance. In general any type declaration in COOL has the form x:C. Every variable must have a type declaration at the point it is introduced. In Cool we also have the concept of subtype. Each class in COOL has a self type, and the “SELF_TYPE” refers to that. For a more formal introduction to COOL we can refer the Cool Manual.

AngelScript

AngelScript is a free, open source, flexible, and cross-platform scripting library meant to be embedded in applications. The purpose is to provide an easy to use library that is powerful, but that isn’t weighed down by a large amount of rarely used features. Below is the feature:

  • Familiar syntax – The script syntax is similar to that of C or C++, with only a few differences.
  • Statically typed – Unlike most scripting languages that are dynamically typed this one uses the same static types as C++, and applications can register additional types.
  • Object oriented – The script language allows for declaration of classes, with support for single inheritance and polymorphism through interfaces.
  • Object handles – Pointers are not safe in a scripted environment, so AngelScript uses object handles instead. Object handles are almost like smart pointers, that control the life time of the object they hold.
  • Sandboxing – The library provides a secure environment for the scripts, i.e. the scripts can only access what the application explicitly exposes, and any built-in script objects are completely secure.
  • International support – The script files can be encoded in ASCII or UTF-8. String constants can include UTF-8 encoded characters directly or can use escape sequences to add specific unicode code points. UTF-16 encoded string literals is also supported.

C–

C– is a compiler-target language. The idea is that a compiler for a high-level language translates programs
into into C–, leaving the C– compiler to generate native code. C–’s major goals are these:

  • C– encapsulates compilation techniques that are well understood, but difficult to implement. Such techniques include instruction selection, register allocation, instruction scheduling, and optimization of imperative code with loops.
  • C– is a language, rather than a library (such as gcc’s RTL back end). As such, it has a concrete syntax that can be read by people, and a semantics that is independent of any particular implementation.
  • C– is a portable assembly language. It is, by design, as low-level as possible while still concealing details of the particular machine architecture.
  • C– is independent of both source programming language and target architecture. Its design accom-modates a variety of source languages and leaves room for back-end optimization, all without upcalls from the back end to the front end.
  • C– is efficient—or at least admits efficient implementation. So C– provides almost as much flexibility and performance (assuming a good C– compiler) as a custom code generator.

GO

Go is the language developed by Google. Sometimes I like the syntax of Go little better than C++ for building a language. It has a clear syntax.

 

Other languages that influence my design are listed in the bibliography section.

Final language

Well I could not decide, and in general I am not building a reference implementation of a different langage. So I prefer to build my own which is inspired by a lot of other languages. After what is the fun if the language is not a new one. I will call it “Odra“. Reason is I am willing to write a small game engine tutorial also, and this will be the language that I will be using there.

In the next article we will talk about the syntax of the language.

Bibliography

C++11 Move semantics, rvalue reference

In this article we will discuss the move semantics for C++. We will try to figure out what exactly move is.

Problem Statement

Copying is not the optimal solution in all situations. Some situations demand moving as copying may mean duplication of resources and it may be a intensive task.

Another problem arises due to temporaries. These temporaries may blog memory and slow down C++ execution.

Solution

Solution comes inform of the move semantics. We will gradually discover what this is.

rvalue reference

RValues is a new addition to C++11. We will see what its purpose is and why it was implemented.

The original definition of lvalues and rvalues from  is as follows:

As per C style definition an lvalue is an expression that may appear on the left or on the right hand side of an assignment, whereas an rvalue is an expression that can only appear on the right hand side of an assignment.

  int a = 42;
  int b = 43;

  // a and b are both l-values:
  a = b; // ok
  b = a; // ok
  a = a * b; // ok

  // a * b is an rvalue:
  int c = a * b; // ok, rvalue on right hand side of assignment
  a * b = 42; // error, rvalue on left hand side of assignment

C++ with its user-defined types has introduced some subtleties regarding modifiability and assignability that cause this definition to be incorrect. So now what we tell lvalue is an expression that represents a memory location., this lvalue lets us take the address of the location. What is a rvalue? Simple, what ever is not a lvalue.

Now let us formally define these terms and properties a little better.

For first what is an expression?

  • A expression is a sequence of operators and operands. A expression is a statement that specifies a computation. It tells the computer or say C++ what to do.
  • A expression can produce a value like 1+2;// Its value is 3.
  • A expression can have side effects too like a function call.
  • A expression can be simple or complex.
  • Each expression has a type and a value category i.e. if the expression is lvalue, rvalue etc.

 lvalue

An lvalue is an expression that identifies a non-temporary object or a non-member function.

  • Address of a lvalue can be taken.
  • Modifiable i.e. non const lvalue can be used on the left side of the =
  • lvalue can be used to initialize the lvalue reference.
  • Some times when permitted lvalue can have incomplete type.

Examples:

  • The name of a variable or function in scope, regardless of type, such as std::cin or std::endl. Even if the variable’s type is rvalue reference, the expression consisting of its name is an lvalue expression.
  • Function call or overloaded operator expression if the function’s or overloaded operator’s return type is an lvalue reference, such as std::getline(std::cin, str) or std::cout << 1 or str1 = str2 or ++iter
  • Built-in pre-increment and pre-decrement, dereference, assignment and compound assignment, subscript (except on an array xvalue), member access (except for non-static non-reference members of xvalues, member enumerators, and non-static member functions), member access through pointer to data member if the left-hand operand is lvalue, comma operator if the right-hand operand is lvalue, ternary conditional if the second and third operands are lvalues.
  • Cast expression to lvalue reference type.
  • String literal
  • Function call expression if the function’s return type is rvalue reference to function type
  • Cast expression to rvalue reference to function.

prvalue

A pure rvalue (prvalue) is an expression that identifies a temporary object (or a subobject thereof) or is a value not associated with any object.

  •  It can be a rvalue
  • a prvalue cannot be polymorphic: the dynamic type of the object it identifies is always the type of the expression
  • a non-class non-array prvalue cannot be const-qualified.
  • a prvalue cannot have incomplete type (except for type void, see below)
  • The expressions obj.func and ptr->func, where func is a non-static member function, and the expressions obj.*mfp and ptr->*mfp where mfp is a pointer to member function, are classified as prvalue expressions, but they cannot be used to initialize references, as function arguments, or for any purpose at all, except as the left-hand argument of a function call expression, e.g. (pobj->*ptr)(args).
  • Function call expressions returning void, cast expressions to void, and throw-expressions are classified as prvalue expressions, but they cannot be used to initialize references or as function arguments. They can be used in some contexts (e.g. on a line of its own, as the left argument of the comma operator, etc) and in the return statement in a function returning void

Examples:

  • Literal (except string literal), such as 42 or true or nullptr.
  • Function call or overloaded operator expression if the function’s or the overloaded operator’s return type is not a reference, such as str.substr(1, 2) or str1 + str2
  • Built-in post-increment and post-decrement , arithmetic and logical operators, comparison operators, address-of operator, member access for a member enumerator, a non-static member function, or a non-static non-reference data member of an rvalue, member access through pointer to a data member of rvalue or to a non-static member function, comma operator where the right-hand operand is rvalue, ternary conditional where either second or third operands aren’t lvalues.
  • Cast expression to any type other than reference type.
  • Lambda expressions, such as [](int x){return x*x;}

xvalue

An xvalue is an expression that identifies an “eXpiring” object, that is, the object that may be moved from. The object identified by an xvalue expression may be a nameless temporary, it may be a named object in scope, or any other kind of object, but if used as a function argument, xvalue will always bind to the rvalue reference overload if available.

  • It can be either rvalue or
  • it can also be a gvalue
  • Like prvalues, xvalues bind to rvalue references
  • Unlike prvalues, an xvalue may be polymorphic, and a non-class xvalue may be cv-qualified.

Examples:

  • A function call or overloaded operator expression if the function’s or the overloaded operator’s return type is an rvalue reference to object type, such as std::move(val)
  • A cast expression to an rvalue reference to object type, such as static_cast<T&&>(val) or (T&&)val
  • a non-static class member access expression, in which the object expression is an xvalue
  • A pointer-to-member expression in which the first operand is an xvalue and the second operand is a pointer to data member.

gvalue

A glvalue (“generalized” lvalue) is an expression that is either an lvalue or an xvalue.

  • Mostly its properties are as applies to pre-C++11 lvalues
  • A glvalue may be implicitly converted to prvalue with lvalue-to-rvalue, array-to-pointer, or function-to-pointer implicit conversion.
  • A glvalue may be polymorphic: the dynamic type of the object it identifies is not necessarily the static type of the expression.

rvalue

An rvalue is an expression that is either a prvalue or an xvalue.

  • It has properties that apply to both xvalues and prvalues, which means they apply to the pre-C++11 rvalues as well
  • Address of an rvalue may not be taken: &int(), &i++[3], &42, and &std::move(val) are invalid.
  • An rvalue may be used to initialize a const lvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.
  • An rvalue may be used to initialize an rvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.
  • When used as a function argument and when two overloads of the function are available, one taking rvalue reference parameter and the other taking lvalue reference to const parameter, rvalues bind to the rvalue reference overload (thus, if both copy and move constructors are available, rvalue arguments invoke the move constructor, and likewise with copy and move assignment operators).

Moving

Lets say we have a 3D model class. The model class holds textures that are image files, vertex points that can spawn to thousands, color info for each vertex. Say like

class Vertex {
  // Members not imp
public:
  void addVertex ( /*vertex type*/ ) {

  }
  ~Vertex ( ) {
    // Destroy verted
  }
};

class Texture {
  // Members not imp
public:
  void load (/*info*/ ) {
    // Heavy duty image loading
  }
  ~Texture ( ) {
    // Destroy 
  }
};

class Model3D {
private:
  Vertex* _ver;
  Texture* _tex;
public:
  void initialize ( ) {
    _ver = new Vertex;
    _tex = new Texture;
    for ( int i = 0; i<10000; ++i ) {
      // Some more processing
      _ver->addVertex ( );
    }
    for ( int i = 0; i<500; ++i ) {
      _tex->load ( );
    }

  }
  ~Model3D ( ) {
    delete _ver;
    delete _tex;
  }
};

Model3D retGraphics ( ) {
  Model3D g;
  // Do some operation and return
  return g;
}

Model3D g1 = retGraphics ( );

Here as you can see the ThreeD model class does some heavy duty vertex and texture loading. Now take a look at the statement Model3D g1 = retGraphics ( );. This statement can be converted to following pseudo code

Model3D tempG;
Model3D retGraphics ( ) {
  Model3D g;
  // Do some operation and return
  // g will die with the scope, so copy it to a temp object
  tempG = g; // Clone the resources call Model3D::operator =( Model3D& ) on tempG 
  g->~Model3D( );
}
Model3D g1 = tempG; // Clone tempG. Call Model3D::operator =( Model3D& ) on g1
tempG->~Model3D ( );

As you see there is a temporary involved. That means the vertex and texture destruction and loading happens  2ce. This is a time consuming and unnecessary process. So now the intelligent programmer is left with writing some code that can actually do the swapping of resource, rather than let the resource get destroyed. This is again time consuming and boring work, but all have to do it increasing the source size. Won’t it be good if the language did it, hence reducing the burden from the programmer? Well C++ does exactly that with the move functionality.So it does something like

Model3D& Model3D::operator = ( <move type> rhs ) {
  //swap _ver
  //swap _tex
}

This is the reason C++ creates a overload with the move type, which is special type to tell the compiler to move the resources rather than do the delete and construct operation. With the move type in play the compiler deals with the following choice:

  • Move type must be a reference
  • when there is a choice between two overloads where one is an ordinary reference and the other is the mystery type, then rvalues must prefer the mystery type
  • lvalues must prefer the ordinary reference

So what exactly is this move type? This is the rvalue reference i.e. Model3D&&.

Model3D& is called the lvalue refernce.  So what are the properties of the rvalue reference now?

  • During function overload resolution lvalue prefer lvalue reference and rvalue prefer rvalue reference.
void f ( Model3D& m); // Lvalue reference overload.
void f ( Model3D&& m); // rvalue refernce overload.

f ( g1 ); // Here g1 is lvalue, so call void f ( Model3D& m );
f ( retGraphics ( ) ); // Here rvalue is needed. so void f ( Model3D&& m ); is called.
  • We can overload any function with rvalue. But mostly in practive the copy constructor and assignment operator.

In the next article we will look at it in more details.

Bibliography

C++ Rvalue References Explained by Thomas Becker.

Lvalues and Rvalues by Mikael Kilpeläinen

C++11 Constructors and Copy assignment – Part 2

Topics Covered

In this section we will have a look at more C++ constructors. The following will be covered:

  1. Copy Constructor
  2. Copy Assignment Operators
  3. Move Constructor

 Copy Constructor

Definition

General Definition

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments .

Example:

class X {
public:
  X ( const X& );  // Copy Constructor
  X ( const X&, int = 1 );  // Copy Constructor
};

Here the copy constructor is public. This class is call Copy Constructible.

Saying this what happens in the following case?

class X {
public:
  X ( X& x, int i );
  X ( ) { };
};

X::X ( X& x, int i = 0) {

}

We will discuss more of these cases when we dive deeper in another article.

Like normal constructors these can also be deleted, or default.

X ( const X& ) = default; // Forcing a copy constructor to be generated by the compiler
X ( const X& ) = delete; // Avoiding implicit default constructor

Now the question is; do we always need to pass a reference in copy constructor?

Well lets see the case below:

class X {
public:
  X ( const X v);
};

// Somewhere else in code
X a;
X b = a;

Now what will happen? Here X b = a;  the code will look like b( X v = a). Now this is again a copy constructor call. This will happen like this recursively until we are out of stack space and the program will crash. So this is not allowed. This will throw up error telling this is illegal copy constructor.

A class can have multiple copy constructors, e.g.

class X {
public:
  X ( const X& );
  X ( X& );
};

A member function template is never instantiated to produce a copy constructor signature.  Like

class X {
public:
 template<typename T>
 X ( T );
 X ( );
};

X a;
void foo ( ) {
 X b ( a ); // does not instantiate the member template to produce X::X<X>(X);
}

In this case the implicitly declared copy constructor is used.

The reason being follows:

  1. The template can be instantiated to mimic a copy constructor but as per the standard statement it is not a copy constructor (If you haven’t seen the definition see again, it explicitly tells as non-templated). So this means the class doesn’t define one.
  2. The compiler now generates a copy-constructor in the right circumstance. So say the compiler also instantiates this templated code. Then when the time to choose comes, the over loading resolution chooses the non templated function rather than the templated one as it does for other functions.

Implicitly-declared copy constructor

If no user-defined copy constructors are provided for a class type the compiler will always declare a copy constructor with the following type

class X {
public:
  inline X ( const X& );  // It is public and inline
};

The const modifier is applied only if the following conditions are met:

  • All direct and virtual bases of “X” have copy constructors with references to const or to const volatile as their first parameters.
  • All non-static members of “X” have copy constructors with references to const or to const volatile as their first parameters
Some facts
  • The implicitly-defined copy constructor for a non-union class X performs a member-wise copy of its bases and members.
  • The order of initialization is the same as the order of initialization of bases and members in a user-defined constructor.
  • The implicitly-defined copy constructor for a union X copies the object representation of X.

Deleted implicitly-declared copy constructor

The implicitly-declared or defaulted copy constructor for class X is defined as deleted or in simpler pre C++11 terms undefined (the compiler cannot define them) if the following conditions are met:

  • X has non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors)
  • X has direct or virtual base class that cannot be copied (has deleted, inaccessible, or ambiguous copy constructors)
  • X has direct or virtual base class with a deleted or inaccessible destructor.

Trivial copy constructor

A trivial copy constructor is a constructor that creates a byte-wise copy of the object representation of the argument and performs no other action. Objects with trivial copy constructors can be copied by copying their object representations manually e.g. with std::memmove.  All data types compatible with the C language (POD types) are trivially copyable.

The copy constructor for class X is trivial if all of the following is true:

  • It is not user-provided (that is, it is implicitly-defined or defaulted), and if it is defaulted, its signature is the same as implicitly-defined
  • X has no virtual member functions
  • X has no virtual base classes
  • The copy constructor selected for every direct base of X is trivial
  • The copy constructor selected for every non-static class type (or array of class type) member of X is trivial

Implicitly-defined copy constructor

If the implicitly-declared copy constructor is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler.

  • For union types, the implicitly-defined copy constructor copies the object representation (as by std::memmove).
  • For non-union class types (class and struct), the constructor performs full member-wise copy of the object’s bases and non-static members in their initialization order using direct initialization.

Usage

class X {
public:
  X ( const X& );  // Copy Constructor
};

X a;
// General initialization
X b = a; 
X b ( a );
// Function argument passing
void f ( const X v ); // Function definition
f ( a );
// Return 
void f ( ) {
  X a;
  return a;
}

If a class X only has a copy constructor with a parameter of type X&, an initializer of type const X or volatile X cannot initialize an object of type (possibly cv-qualified) X

class X {
public:
  X ( ) ; // default constructor
  X ( X& ) ; // copy constructor with a non-const parameter
};
const X a;
X b = a;  // error: X::X(X&) cannot copy a into b

 

Copy Assignment Operator

Definition

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&. As with any function and constructor they can be default or deleted.

class X {
public:
  X& operator=( X );
  X& operator=( const X& );
  X& operator=( const X& ) = default;
  X& operator=( const X& ) = delete;
};

 

Chitra – A game engine from scratch using C++ and SDL – Introduction

A game engine is a software framework designed for the creation and development of video games. Video game developers use them to create games for video game consoles, mobile devices and personal computers. The core functionality typically provided by a game engine includes a rendering engine, a physics engine or collision detection, sound, scripting, animation, artificial intelligence, networking etc. This is an abstraction that brings the world we see into life.

In these tutorial series we will go through creating a game engine from some basic components. We will explore the concepts, data-structures and theory behind them. We will try to create 2D engine first and then venture into 3D.

To do so we will use the following software.

  1. Geometry

Forking out of Urho3D -> Konark

I have forked out of a excellent game engine Urho3D. I have named it as Konark (Named after a beautiful temple at Odisha – India). I wish to add some twists of my own. I will keep on updating it with some changes.

What is “Urho3D”?

Urho3D is greatly inspired by OGRE and Horde3D. There has been some additional research that has gone into it. It has the following features:

Features

Direct3D9 or OpenGL rendering (Shader Model 2, OpenGL 2.0 or OpenGL ES 2.0 required as minimum)
HLSL or GLSL shaders + caching of HLSL bytecode
Configurable rendering pipeline. Default implementations for forward, light pre-pass and deferred rendering
Component based scene model
Skeletal (with hardware skinning), vertex morph and node animation
Automatic instancing on SM3 capable hardware
Point, spot and directional lights
Shadow mapping for all light types; cascaded shadow maps for directional lights
Particle rendering
Geomipmapped terrain
Static and skinned decals
Auxiliary view rendering (reflections etc.)
Geometry, material & animation LOD
Software rasterized occlusion culling
Post-processing
HDR renderingv1.31
2D sprites and particles that integrate into the 3D scenev1.31
Task-based multithreading
Hierarchical performance profiler
Scene and object load/save in binary and XML format
Keyframe animation of object attributesnew
Background loading of resourcesnew
Keyboard, mouse, joystick and touch input (if available)
Cross-platform support using SDL 2.0 (currently runs on Windows, Linux, Mac OS X, Android, iOS, and Raspberry Piv1.3)
Physics using Bullet
2D physics using Box2Dnew
Scripting using AngelScript
Alternative script interface using Luav1.3 or LuaJITv1.31 (on Windows, Linux, Mac OS X, Android, and Raspberry Pi)
Networking using kNet + possibility to make HTTP requestsv1.3
Pathfinding using Recast/Detourv1.23
Image loading using stb_image + DDS / KTX / PVR compressed texture support
2D and “3D” audio playback, Ogg Vorbis support using stb_vorbis + WAV format support
TrueType font rendering using FreeType, AngelCode bitmap fonts are also supported
Unicode string support
Inbuilt UI system
Scene editor and UI-layout editor implemented in script with undo & redo capabilities
Model/scene/animation/material import from formats supported by Open Asset Import Library
Alternative model/animation import from OGRE mesh.xml and skeleton.xml files
Supported build tools and IDEs: Visual Studio, Xcode, Eclipse, CodeBlocks, GCC, LLVM/Clang, MinGW-W64
Supports both 32-bit and 64-bitv1.3 build
Build as single external library v1.3 (can be linked against statically or dynamically)

 

I wish to add boost geometry support and all the matrix and vector calculations will be using GLM(OpenGL Mathematics).

 

C++11 Constructors

What is a Constructor

Construction is an important part of the object creation. Unlike the ‘malloc’  function in C which just gets the system memory and returns the handle to it, the ‘new’ operator does more things. Constructors are also invoked when the object is declared. This means constructors are used with both stack-based and heap-based allocation. It is this construction phase which brings life to just allocated chunk of memory. In this article we will discuss briefly the different constructs for construction available in C++11.

As per the C++ reference Constructor is a special member function. Constructors do not have names.  A declaration of a constructor uses a function declarator of the for:

ptr-declarator ( parameter-declaration-clause ) exception-specification-opt attribute-specifier-seqopt

It means syntactically, a constructor is specified by a method name that is the same as the class name.

A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name look-up. A constructor can be invoked for a const, volatile or const volatile object. const and volatile semantics are not applied on an object under construction. They come into effect when the constructor for the most derived object ends. Following is the ‘order of construction’:

  1. It calls base class and member constructors in the order of declaration.
  2. If the class is derived from virtual base classes, it initializes the object’s virtual base pointers.
  3. If the class has or inherits virtual functions, it initializes the object’s virtual function pointers. Virtual function pointers point to the class’s virtual function table to enable correct binding of virtual function calls to code.
  4. It executes any code in its function body.

A constructor never has a return type and may or may not have parameters.  A constructor with no parameters is called the default constructor.

As of C++11 the default constructors have the following syntax:


ClassName ( ) ;  //  Declaration of a default constructor
ClassName :: ClassName ( ) {/*body*/} // Definition of the constructor outside the class body
ClassName() = delete ; //  Inhibiting the automatic generation of a default constructor (since C++11)
ClassName() = default ; // Explicitly forcing the automatic generation of a default constructor  (since C++11)


 

Default Constructor

Default constructor for a class X is a constructor of class X that can be called without an argument.  What this means is that the default constructor can have no arguments or all arguments should have a default value. There are many contexts in which you may have to provide a default constructor for a class or else the compiler will throw errors. But why is a default constructor needed?

Lets take the example of the class X

class X{int _i; X(int i){}};

now lets say we need 10 stack objects i.e. an array:

X x[10];

Here the C++ implementation wont know what to specify the default values. The compiler will throw error.

So what is happening here? Why is the error coming.

If no user-defined constructor exists for a class X and one is needed, the compiler implicitly declares a default parameter-less constructor for X i.e. ‘X::X()’.

Default constructor is also needed when you want to initialize your object with ‘STL’.

Even try to compile the following code :

class X{

const int _i;

}; // This will not compile as const is not given a value.

class Y{

int &_iref;

}; // The Ref holds no value so this will also not compile.


 

Additions in C++11

  • C++11 Explicitly Defaulted Constructors

In pre C++11 versions if your class required a number of explicit constructors accepting arguments but also a default constructor that does nothing, you had to explicitly write your empty default constructor as follows:

class X{

int _i;

public:

X(){/*Nothing inside*/} // You have to explcitly write it with a null body.

X(int i);

}

In this case if ‘X(int i)’ is defined then compiler will not generate any default constructor. To avoid having to write empty default constructors manually, C++11 introduces the concept of ‘explicitly defaulted constructors’. This allows you to write the class definition as follows without the need to implement it in the implementation file.

class X{

int _i;

public:

X() = default;

X(int i);

}
  • C++11 Explicitly Deleted Constructors

We can define a class for which we do not want to write any constructors and we also do not want the compiler to generate the default constructor. In that case we need to explicitly ‘delete‘ the default constructor. Deleted constructors also give us simple language to prevent problematic type promotions from occurring in arguments to functions.

class X{

int _i;

public:

X() = delete;

}

 

We will take a more closer look at the C++ initializers and copy constructor in the next blog.