Thursday, March 9, 2017

Multi-character literal (Multiple characters inside single quotes) Vs char literal in C, C++

Any character with in single quotes('a') is a character literal  (character constant) and a string literal is a set of characters with in double quotes ("Hello").
And if we have multiple characters in side single quote('aa') ,it is a multi-character literal

Before going to the multi-character literal we will check how these literals are considered (as value and type) by compiler. In C language type of character literal is int. So size of char literal is 4 bytes in 32 bit architecture. Where as in C++ the type of character literal is char and size is 1 byte.

Save following program with .c and .cpp extension and run with c and cpp compiler.

Wednesday, March 8, 2017

When to use dynamic_cast and static_cast in C++

Dynamic Cast:
  • Dynamic cast is used to convert a pointer (or reference) to base type to pointer (or reference) to derived type, iff the base pointer/reference refers to derived type. This is called down casting. (Base -> Derived)
  • This type of casting is used when these two types are polymorphic (means base class should have virtual methods).
  • No need of explicit type casting when we want to convert a pointer (or reference) to derived type to pointer (or reference) to base type. This is called up casting. (Derived-> Base )
  • If you use dynamic_cast for non-polymorphic classed it will through compile time error
  • This cast is mainly used to execute the derived type specific functionality when we have base class pointer/reference. (Throgh base pointer/reference we cannot access derived type specific fucntionality)
  • dynamic_cast safely convers to derived type in run-time, if it fails to convert it will return NULL when target is pointer type, throws bad_cast exception when target type to convert is reference.
Example:

Sunday, January 8, 2017

C++11 Features (Part 1)


Here i'm listing some of the C++ 11 features we can use frequently.

1.Auto
2.Range Based for loop
3.Strongly typed enums
4.Forward enum declaration

To use C++ 11 features when compiling in commad line use any of the following flags

  $g++ -o myprog myprog.cpp -std=c++0x  (or)  
  $g++ -o myprog myprog.cpp -std=gnu++0x (or)  
  $g++ -o myprog myprog.cpp -std=c++11    

Auto:
Before C++11 auto keyword is used in the storage class, from C++11 it is used as type inference, means automatic deduction of data type of an expression.
We can use auto inside the blocks, namespaces, and for loop initialization etc. Using auto we can reduce writing the some complex type declarations like iterators intialization in loop.