This is 3rd blog post about introduction to c++ 11 standard with examples. In this post we will study about c++ 11 features enum call,static_assert and delegating constructor.

introduction to c++ 11 standard with examples (tutorial 3)introduction to c++ 11 standard with examples (tutorial 3)

enum class

In c++ 03 enum is an integer. so following code will give output “apple is equal to dog”.

In c++ 11 enum class is an class. so following code will give compile time error “error: no match for ‘operator==’ (operand types are ‘animal’ and ‘fruit’)”. The error happens because we have not provided == operator overloading.

c++ 11 static_assert ( compile time assert )

c++ 03 provides run time assert.

c++ 11 provides compile time assert through static_assert keyword.  static_assert performs compile time assertion checking. If the assertion is false, the complier will output the specified error message.

When expression (sizeof(long) >= 8 ) would fail, compiler shows error message “64-bit code generation not enabled/supported.” at compile time.

c++ 11 delegating constructor

c++ 11 delegating constructor is a very simple concept. Before going into the details let us make a very simple use case for designing a class. we will design the class in c++03 standard first and later on in c++ 11.

Suppose we are going to design a class contact with three data members name, phone number and email address. so our class may look like as

The above class is not a good design of a class because we have not provided a constructor. what constructor does? it initializes its data members.

So far we have provided a constructor in our class contact. it would initialize its data members name, phone_number and email_address.

can you think what is issue with this design?

The design ensures that it will create an object of class contact provided all information name, phone number and email is present. what if there is no email or phone or name is present? so in this case we have to provide other constructors to make an different object of class contact.

Reimplementing above design using c++ 11 delegating constructor

Delegating constructors prevent code duplication. The meaning of delegating a constructor means one constructor can call another to initialize the object.