May 132017
 

Generic programming, loosely means that the code we have written is type-independent. It is a larger topic, macros in C language also comes under generic programming. In this post we are only discussing generic pointers.

Continue reading »

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 ) ...

Or

    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 »