Feb 062013

While comparing a variable with a constant (literal) in C/C++ language, which of the two ways of comparison should we use ?

    if( x == 2 ) ...

    if( ptr == NULL ) ...


    if( 2 == x ) ...

    if( NULL == ptr ) ...

In the first comparison we are writing variable on the Left side of == and literal (constant) on right side. whereas, in the second form we are writing the literal (2, NULL, etc.) on the left side of ==.
Continue reading »

Feb 052013

Object of a class can be created dynamically on heap or statically on Stack or Data Area. If we have a class MyClass, then the below objects will be created on heap.

// Operator: New
MyClass *ptr1 = new MyClass(); // Crating object of MyClass on heap.

// Operator: New-Array
MyClass *ptr2 = new MyClass[10]; // Create an array of object MyClass on heap.

However, objects can also be created statically as below:

// Global object created at load time in the data area
MyClass obj1;

void func()
    // Object getting created on the Stack 
    // (Activation record of function func).
    MyClass obj2;

    // Global object created at load time in the data area
    static MyClass obj3;

Design a class which does not allow any object to be created on heap.
Continue reading »

Feb 052013

Write a class, such that user can create its object on heap (using new) but user should not be able to create its object on stack or data area. i.e if the class is MyClass, then

MyClass stackObj;     // Should give compile time error.
MyClass *heapobj = new MyClass;      // This should be OK, & allowed.

Give the definition of class, MyClass (How should you change the scope or anything else of constructor / destructor / assignment operator or any other function, etc.). Continue reading »

Nov 062012

sizeof operator returns size in bytes. For example, In an implementation where 2 bytes (16bits) of memory is allocated to an int type, the below code will output 2

int x = 10;
printf("%d", sizeof(x)); // Output amount of memory allocated to int data type.

We talked about the sizeof operator in great detail in the last post.

If we use sizeof operator on arrays, as shown below:

int arr[10];
printf("%d", sizeof(arr)); //Will output 20

the output will be 20.

But sometimes, its not a good idea to use this operator on arrays.
Continue reading »