Category Archives: Concepts

Type casting in C++ – Part 1

Type casting frequently arises in real life programming. This post concentrates on type conversion of fundamental data types. Type casting is the process of converting from one data type to another. In C++, type casting is automatic in some situations. These are called implicit conversions.

For example
char c = ‘A’;
int ch_code = c;
short s_val = 1024;
int i_val = s_val;
Here the value of “c” is automatically promoted to an int as we are assigning a smaller type into a bigger type. The second case is also similar. This is also called a promotion. There is no truncation in these cases. Other examples of this type include int to float/double, float to double, boolean to int etc…
Implicit type conversion also happen when a bigger type is assigned to smaller type. This might result in truncation/data loss if the source data which cannot fit in the destination type. Some compilers gives a warning when we are using such a conversion. This can be avoided by explicit conversion.
int ch_code = 97;
char ch = ch_code; // no data loss as 97 is within the range of char type; represents the character ‘a’
float pi = 3.14159;
int i_pi = (int)pi; //decimal part is truncated; explicit type conversion
If the truncated integer value is bigger than the integer type, the behavior is undefined.

If a negative integer type is converted to a unsigned type, the resulting value would be 2’s compliment bit representation interpreted as a positive integer.

For example the following code
short x = -32768;
unsigned short y = x;
Assigns a value of 32768 to y. The least value has become the greatest value in this case.

If you are converting an integer to boolean type, all non-zero value will be converted to 1 including negative and positive values which are considered true. 0 is considered false.
int x = -10;
bool b = x; // b is assigned 1, i.e true
x = 10;
b = x; //b is 1 here also
x = 0;
b = x; //b is 0,i.e false

In the later posts, we will look at type conversions between non fundamental data types like pointers and classes.

C++ STL Algorithms – Sort – Part-2

In the last post, the basic use of STL sort() method is explained. In this post, I will discuss some more options available with this method.
We have seen in the previous post that sort takes the beginning and ending of the array as arguments.
sort( array.begin(), array.end() );
In addition to those parameters, it can also take a third parameter (predicate) which decides the ordering of the elements. If we do not pass the third parameter, the default ordering is assumed. For integer data types such as int,  float, char etc, ascending order is followed. For strings alphabetical order is followed. To sort an array of integers in descending order, simply call the sort routine like this.

sort( array.begin(), array.end(), greater<int>() );

std::greater is a built in comparator object provided by STL. we have to pass the type of objects to be sorted. similarly we have std::less, std::less_equal, std::greater_equal etc…

So far we are sorting only built in data types such as int, double and library class string. We can also sort objects of user defined classes also.

For example in the following program I have defined a class called Pair, which contains two fields. To sort user defined/custom data types we also have to write the comparison functions to decide the ordering. We can sort Pairs either according to the first value or the second value. I have written two comparator functions and passed these while sorting. 

Here is the code which explains these concepts.


C++ STL Algorithms – Sort- Part-1

Sorting is one of the most widely used algorithmic primitive in programming. 
C++ Standard Template Library (STL) provides an efficient implementation of the sort algorithm. It is always better to use this algorithm instead of writing our own implementation because of the following benefits.
  • It’s performance would surely be better than your own implementation. It’s implementation conforms to the C++ standard bench marks and tested by a lot of people. The library version takes advantage of the combination of multiple sorting algorithms to achieve the maximum performance.
  • Writing our own version is error prone and bugs can easily be overlooked.

Here is a simple program which demonstrates the use of library sort() routine to sort an array as well as a vector. 

The sort() method at the minimum requires two parameters; the start of the list and the end of the list. Note that the end should always point to one element beyond the last element. It sorts the element ranging between [begin, end) i.e starting from the first element till the end excluding the last.


For arrays, we know that the array name indicates the address of the first element. If we add the size of the array to the starting address, we get the address of next to last element.

For vectors, there are built-in methods begin() and end() to indicate the starting and ending elements.


    #include <iostream>
    #include <algorithm> //included for using sort
    #include <vector>
    #include <string>
    using namespace std;

    int main()
    {
    int arr[5] = {9, 6, 36, 24, 42};
    int arrSize = sizeof(arr)/sizeof(arr[0]);

    sort(arr, arr+arrSize); //sorts the given numbers in ascending order

    for( int i=0; i < arrSize; i++ )
    {
    cout << arr[i] << " ";
    }
    cout << endl;

    vector<string> names;
    names.push_back("Himalayas");
    names.push_back("Alphs");
    names.push_back("Vindhya");
    names.push_back("Aravali");

    sort( names.begin(), names.end());//sorts the names in alphabetical order

    for( int i = 0; i < names.size(); i++ )
    {
    cout << names[i] << " ";
    }

    cout << endl;

    return 0;

    }

    Size of an empty object in C++

    What is the size of an empty object in C++?
    This is one of the most frequently asked questions on forums.
    For example consider the following code snippet.
    class A
    {
    };
    A aOb;
    cout << sizeof(aOb);
    The size of an empty object is not zero to ensure that the addresses of two different objects will be different. For the same reason, “new” always returns pointers to distinct objects.
    On most of the compilers, it would return 1 byte. Even if the class contains only member functions and no data members, this is applicable.
    However if the class contains at least one virtual method, the sizeof() operator returns 4 bytes on a typical compiler. This is so because every class with at least one virtual function has a pointer to vtable stored which is helpful in dynamic binding.

    class B
    {
       virtual void func()
       {
       }
    };

    B b;
    cout << sizeof(b);

    constant pointers and pointer to constant

    In this post we talk a little bit about the constant pointers and pointer to a constant and the difference between them.
    In C programming, pointer is a crucial concept and it is always good to have a clear understanding of the fundamentals.
    Constant pointers:
    Constant pointer as the name indicates is a pointer whose value can not be changed. In another way, once a pointer is initialized with an address of a variable, it can not point to any other variable further. We can also say it is a read-only pointer. For example, take a look the following code snippet.
    int var1 = 1, var2 = 2;
    int * const pVar = &var1; //constant pointer to an integer
    pVar = &var2; //Incorrect, gives a compilation error
    We have declared two variables var1, and var2. A constant pointer pVar is initialized to point to var1. In the next statement we are trying to point pVar to var2 which is incorrect and gives a compilation error as follows.
    [Error] assignment of read-only variable ‘pVar1’
    A constant pointer is useless if we don’t initialize it with any address. The compiler gives no error in this case, but that pointer is useless because it can not point to any object further.
    int count = 10;
    int * const pCount;//Valid code;no compiler error
    pCount = &count; //Invalid; compiler error
    Pointer to constant:
    A pointer to a constant object. This means that we can not modify the object addressed by this pointer. But we can always read the object via this pointer and also we can make this pointer to address another object. To understand this, let us look at the following code snippet.
    int var = 1, other = 2;
    const int *pVar =&var; //pointer to a constant
    *pVar = 10;//error:assignment of read-only location’*pVar1′

    printf(“%d”, *pVar); // Valid; we can always read the value

    pVar = &other; //valid

    We can also create a constant pointer to a constant with the following code. Through this pointer we can not change the value, and we can not make it point to any other object. 

    int var = 100, other = 200;
    const int * const pVar = &var;//constant pointer to a constant
    *pVar = 10;//Error:assignment of read-only location’*pVar1′
    pVar = &other; //Invalid; compiler error
    other = var / 10; //valid; we can read the value