Wednesday, February 29, 2012

How to initialize const variable in C++?

In C++, const keyword is used to create the one time initializer and read-only variable. Once intialised, it is not legal to change the value later. There are two ways to initiaze the const varaibles in C++.
Example:
class cns
{
  private:
    const int val; // declaring const variable
    const static int st=10;   //declaring n initializing using static keyword
  public:
    cns(int aa = 0) :val(aa) // initializing using initialization list
    {
    }
};
main()
{
    cns con(10);
}

P.S: if const variables are not initialised, the values are undefined and it will not allow to change the values. So it is mandatory to initialize the const variables.

Tuesday, February 28, 2012

What is initialization list in C++?

     Generally in C++, we will initalise the variables in constructors using assignment operator. But there are some scenarios like const and reference variables, where we need to initialise at the time of declaration.  Assignement operator will not work for these. C++ provides new feature initialisation list to do this. The initialisation list is required in inheritance and compostion for initialising data members.
     The Initialisation list should add after the constructor, starts with a colon (:) and each variable with the value enclosed in brackets and separated by comma. It will not end with semicolon(;). If you use initialisatin list, no need off explicit assignment  of the variables in constructor. See the sample code below.

class inList{

    private:
        int x,y;
    public:
        inList():x(10),y(20) //initialisation list
        {
            //nothing
        }
        inList(int aX, int aY):x(aX),y(aY) // initialization list
        {
            //nothing
        }
};

int main()
{
    inList l;
    inList iL(100,200);

}

the above two constructors are same as below.

inList()
{
   x=10;
   y=20; 
}

inList(int aX, int aY)
{
   x=aX;
   y=aY;
}

Example for Inheritance:

class inList{

    private:
    public:
        int x,y;
        inList():x(10),y(20)
        {
            //nothing
        }
        inList(int aX, int aY):x(aX),y(aY)
        {
            //nothing
        }
};

class inListDerive: public inList
{
    private:
        int z;
    public:
        inListDerive():z(10),inList(20,30)
        {
            //nothing
        }
        inListDerive(int aZ):z(aZ),inList(20,30)
        {
            //nothing
        }
};
int main()
{
    inListDerive dL; 
    inListDerive dL1(100);

}
    
P.S: To see initialising const variable using initialisation list click here.

Monday, February 27, 2012

What is name mangling?

Name mangling is a process of creating the encoded unique function name with the function name and parameters, so that linker will identify the functions. This will be usefull for the solving the conflicts for the same function name and variables.  Name mangling is also called Name decoration.
     Name mangling is depends on the compiler. It is not same for all compilers.In C++, it will be used in function overloading, and for same variable names in differnt name spaces. Some C compilers also uses name mangling to variables.

void display()
{
    // some code
}

int display(int a)
{
    //some code
}

main()
{
    display();
    display(10);
}

In the above code actual function name is display() with overloading definitions. the curresponding name mangling names are given below.

actual name : display()             mangled name: _Z7displayv
actual name : display(int a)       mangled name: _Z7displayi


Friday, February 24, 2012

Function Overloading in C++!!

Function overloading: As most of you knew, it is another feature in C++. I will explain here about how compiler will know the function overloading and how it works. Function overloading is a concepts writing more than one function with a same name and different parameters. Function return type will not be consider for the function overloading.

          whenever calling the function with parameters, at the time of compilation, compiler will look for the exact match for the function by checking one by one. There are three possibilities. It wont maintain any dynamic table for all the functions.

Match found:  Finding exact match function.
void display(int a); // int as a argument

display(10);  // passing int as argument so exact match
No match found: if no match found, use type conversion and check for the match
void display(int a); //int as a argument


display('a'); // passing char as a argument, it wont find exact match, so type conversion will happen
Ambiguous match: exact match function found , but multiple times with different return type.
void display(int a); // return type as void and int as a argument 
int display(int a);  // Illegal , return type is differnt for the same function name and arguments 
  
display('a'); 

Type conversion:
  • char will convert to int
  • float will convert to double
  • enum will convert to int

Thursday, February 23, 2012

Difference between copy constructor and overloading assignment operator in C++

The basic difference between copy constructor and assignement operator is that
  • Copy constructor is used to create the new object and assigning values of other object to the newly created object
  • Assignment operator is used to assign the values from one object to the already existing object. Here already existing is the main one.
class Copy{

public:
    Copy()  //constructor
    {
        //something
    }
    Copy(const Copy &o) // copy constructor
    {
        //something
    }
    void operator=(const Copy &o) //assignment operator overloading
    {
        //something
    }
};

int main()
{
    Copy C1;
    Copy C2=C1; // calling copy constructor
    Copy C3;
    C3=C2;  // calling assingment operator
}

from the above code snippet, it is clear that in line 21 , it is calling copy constructor because while creating the object C2, we are assigning the other object C1 to C2. where as in line 23 it is calling assignment operator because, we are assigning the object C2 to the already existing object C3. In the above sample code, definition of the copy constructor and assignment operator overloading almost same. but while calling or usage it makes the difference. For more details about copy constructor click here.

Wednesday, February 22, 2012

static variables and static member functions in C++

In C++, there are two uses when static used for C++ classes namely static member variables and static member functions. To access static variables or member functions , no need to create the object. We can directly access by using scope resolution operator with class name. By default static member variable value is zero, need to assign manually for non-zero value.

class staticDemo
{
     public:
         static int stValue; // declaring the static variable
};

int staticDemo::stValue = 10; // initializing static variable

int main()
{
   cout<<"stValue  is "<<staticDemo::stValue; // accessing the static varaible
}
Static member functions: Whatever we discussed above is fine for publice data. If the static data variables are private, we cant access the data directly. So to access the static data, we need static member functions. static member fucntions have two interesting points. 
  • Static member functions dont have this pointer, because they dont have objects.
  • Static member functions can only access static member variables. They cant access non-static member variables.
class staticDemo

{
     private:
         static int stValue; // declaring the static variable
     public:
        static int getValue(); // static method declaration

};

int staticDemo::stValue = 20; // initializing static variable

int staticDemo::getValue()    // static method definition
{
    return staticDemo::stValue;
}

int main()
{

      cout<<"stValue  is "<<staticDemo::getValue(); // accessing the static varaible using static method

}

The basic differenc between non-static and static data is that former one is belongs to object and later one is belongs to class. So for static data to access, no need of object. because of this static data dont have this pointer. Where as for non-static data we need object to access. And each data in the object is different from the other object. Static data is class specific ans non-static data is object specific.


Tuesday, February 21, 2012

What is copy constructor in C++?

Copy constructor: Is a special constructor to initialize a new object from the existing object. This can be used where the new instance is needed before copying the values. below are the some of the scenarios.

  • Creating the new object and assigning the existing object to the newly created object
  • Passing a object by value
  • When a object is returned by function by value

class Copy{

public:
    Copy()  //constructor
    {
       //cout< < "constructor "< < endl;
    }
    Copy(const Copy &o) // copy constructor
    {
        cout< < "copy constructor "< < endl;
    }
};
void test(Copy C)
{
   //something
}
int main()
{
    Copy C1;
    Copy C2=C1; //calling copy constructor (creating n assigining - 1st scenario)
    test(C1);   //calling copy constructor (passing object by value - 2nd scenario)
}

 for copy constructor , need to pass the object as a reference, and not by value. The reason behind this is, when you pass the object by value will call the copy constructor, so calling copy constructor is itself passing object by value, this will become infinite loop until memory reaches empty. Earlier compilers will get run time error, but latest compilers will give the compilation error if you not use reference.

Monday, February 20, 2012

What is Object Slicing in C++ ?

Object slicing: when a derived class object is assigned to a base class object. only base class data will be copied from derived class and derived data will be sliced or ignored. This will occur in C++ , if you try to use call by value. see the sample code in c++.

Object slice prevention:
  • Object slicing can be prevented by making the base class pure virtual, so that base instance will not be allowed.
  • object slicing can't be occurred, if pointers or reference to the objects used, as both pointers of the same size

class base{

public:
int a;
base(){
a = 10;
}
};
class derive: public base
{
public:
int b;
derive()
{
b=20;
}
};

int main()
{
base b;
derive d;
cout< < "size of base class is "< < sizeof(b)< < endl;
cout< < "size of derive class is  "< < sizeof(d)< < endl;
b=d;
cout< < "size of b class is "< < sizeof(b)< < endl;
}


Output:
size of base class is 4
size of derive class is 8
size of b class is 4


From the above sample code, contents of the base class are one int data type and where as for derived class are two int data types. so size of the derived class is more than the base class. and in the example, derived instance is assigned to base instance, so base instance only takes the base contents and it will slice or ignore the extra int data type in derived class.
From the output, the size of the base object is four and size of the derived object is eight. we can observe that even after assigning the derived object to the base object, the size of the base object is four only. it sliced the extra four bytes from the derived object.

Static variable in C!!

In C programming language there are four storage classes namely auto, static, extern and register used for storage location for the variables and scope of the variable. lets see about the static storage class here. To declare the variable to be static , need to use static keyword. this static uses two ways in C.

1.Limiting the scope of the variable to file: Generally for global variables, the scope of the variable is across the application. if you want to limit the scope of the variable to file itself, make the global variable as static.

int g=10; // global value can access anywhere in the application/program
static int s=20; //global and specific to this file. cant  access outside the file
int test()
{
int a; // local to test() function
}

main()
{
int l=30; //local variable cant access outside the main
}

2.Fixed duration: By default all local variable scope will be limited to the function or block only. the data will not be available after reaching out of the block/function. if you want to restore the data use static.
int test()
{
int a=10; // local to test() function
printf("a value is %d\n",a);
a++;
}
int static_test()
{
static  int st=10; // static variable, value will be restored
printf("st value is %d\n",st);
st++;
}
main()
{
printf("** non-static value **\n");
test();
test();
test();
printf("** static value **\n");
static_test();
static_test();
static_test();


Output:
** non-static value **
a value is 10
a value is 10
a value is 10
** static value **
st value is 10
st value is 11
st value is 12

Note: If not initialized, default value set to zero for all static and global variables.

Wednesday, February 15, 2012

What is singleton in C++?

Singleton is a mechanism to restrict the instance of a class to single/unique. This is useful when only one instance across the application is required. There are different ways to implement. Here is the simple one in C++. To implement this in c++ singleton class should satisfy below points.
  • Constructor should be private, so that only member function can instantiate
  • Static pointer variable of the type same class
  • Static member function like getInstance()
After creating the class, initialize the static variable to NULL and implement the member function. In member function check for the static pointer variable for NULL, if it is NULL create the new Instance other wise return that pointer.
#include<iostream>
using namespace std;

class single{
private:
static single *ptr; // pointer variable should be static
single() // constructor should be private
{
}
public:
static single* getInstance();
};

single* single::getInstance() // static function definition
{
if(ptr==NULL)
{
ptr = new single(); creating the instance
cout<<"creating the instance and address is "<<ptr<<endl;
}
else
{
cout<<"instance already created and address is "<<ptr<<endl;
return ptr;
}
}

single* single::ptr=NULL; // initializing static variable;

int main()
{
single *s,*ss,*sss;
s=single::getInstance(); // first time creating the instance
ss=single::getInstance(); // returning the same instance
sss=single::getInstance();// returning the same instance
}

Output:

creating the instance and address is 0x4c49010
instance already created address is 0x4c49010
instance already created address is 0x4c49010


In the sampel code , there are three function calls for creating the Instance. from the output, it is clear that first time only it created the instance and remaining two times it returned the existing pointer. All the time address is same in the output, it means only one instance exists.

Tuesday, February 14, 2012

What is the size of the empty class in c++?


The size of the empty class is always ONE and not ZERO. This is because of below reasons

1. Every object should have some address location to identify, independent of the no.of member variables in the class. Generally the size of the object is the sum of the member variables in the class. if no data is there, one byte of memory allocated to the object to identify. this will help to not conflicting with other empty objects.

2. One more logical reason is that Some times we will use the sizeof() operator in division operation like X%sizeof(emptyclass) and if the value of empty class is zero , application/program will crash.

See the sample code and result:

#include<iostream>
using namespace std;
class Empty
{
};

int main()
{
Empty e1,e2;
cout<< "size of e1 is "<<sizeof(e1)<<" address of e1 is "<<&e1<<endl;
cout<< "size of e2 is "<<sizeof(e2)<<" address of e2 is "<<&e2<<endl;
}


Result:
size of e1 is 1 address of e1 is 0x7fffd925bacf
size of e2 is 1 address of e2 is 0x7fffd925bace


Memory organization in C programming language


Memory is organized in four segments namely text, data, heap and stack segments.

Text segment: This is also called the code segment. all the text will be stored here.

data segment: All the data will be stored here. this segment diveded into BSS and non-BSS portions. In BSS (Block Started by Symbol) all uninitialized static and global variables stored. and initialized and constant variables will be stored in non-BSS portion.

stack segment: All the local variables will be stored here. during the fucntion call stack segment will be used to store the function return address and the local

variables of that function.

Heap segment: this is used for dynamic memory allocation. this memory area can be used by calling malloc, calloc functions.

See the below images for more clarity:


General memory organization




Unix & Windows




GDB: printing complete string

In GDB, generally to print the value of the variable ,we use print or just p. But for the strings or arrays of large size , it wont print whole string or array. We have to do some modifications. By default GDB will print upto 200 characters ,if the string is very large.To change this there is command in GDB

set print elements number-of-elements


Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. Setting number-of-elements to zero means that the printing is unlimited.

(gdb) set print element 20
(gdb)

next time it will print upto 20 characters

(gdb) set print element 50
(gdb)

next time it will print upto 50 characters

(gdb) set print element 0
(gdb)

next time it will print whole array or string

Example:
(gdb) p a
$1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqr"...
(gdb) set print element 0
(gdb) p a
$2 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\000\000\000"
(gdb)

GDB: Changing/Modifying value of the variable

while doing debegging the application using GDB, at the run time variable values can be changed for easy debugging. Assume the there is while loop repeating for 100 times, but if you want to chech the values at 77th iteration. doing step by step will take lot of time and its not a good practice. using the set GDB command we can get this.see the example below

(gdb) p x
$1 = 10
(gdb) set var x = 20
(gdb) p x
$2 = 20
(gdb) set var x = 30
(gdb) p x
$3 = 30
(gdb) set var x = -6
(gdb) p x
$4 = -6
(gdb) p &x
$5 = (int *) 0x7fffffffdc9c
gdb) set {int }0x7fffffffdc9c = -7
gdb) p x
$6 = -7
(gdb)

For changing the variable value, use the set command with var as parameter saying to the GDB that x is a variable. In the above example, in line 14, changed the value of x using address also.

What is GDB?

GDB is a gnu debugger. It will be used to debug the application/program in *nix systems. It is very help full for finding the root caus for the application run time problems. It is available almost in all *nix systems. To use GDB debugger, need to compile the application/program with -g option, so that compiler will create the all symbols for the debugging. GDB will not work if the application compiled without -g option.

gcc -g program-name

gcc command is used for compiling the application for the gdb debugging symbols.

gdb binary-file

gdb command is used to attach the binary file to the gdb. or just use gdb in the command line then attache binary file and use file gdb command to attach the binary file to gdb.

GDB commands



What is constant pointer and pointer to the constant?


C/C++ supports read-only declaration of the variable by using const key word. so that it cant be modified/changed later. values will be assined to the const variables at the time of declaration only.

main()
{
const char a='A'; // declaration n initialization
//a='a'; // Illegal, cant modify the constant variable
}
Pointer to the Constant: This means a pointer to the constant variable like any other variable. But here the difference is, we cant able change the value of the variable. But we can assign as many pointers as we can.

main()
{
char a='A';
const char *ptr = &a; // pointer to the constant
//*ptr='a'; //illegal cant change the constant value
const char *ptr1 = &a; // another pointer to the constant value
}
Constant Pointer: This means its a constant pointer and once it is assigned one address and it cant be reassined to another address. But value can be reassigned/changed.

main()
{
char a='A';
char b='B';
char *const ptr = &a; // pointer to the constant
//ptr = &b; //Illegal another pointer to constant pointer not allowed
*ptr='a'; //legal, can change the value
}

What is linked list?


Linked list is a data structure contains group of nodes. Each node consists of a data variable and a reference or pointer varaible to the next node. The size of the list changes dynamically.



struct node
{
int info;
struct node *next;
};
In the above C code node is the structure name and data variable is info and next is the reference/pointer variable. next can be used to access the next node details.

What is Data structure?


Data structure is the way of organizing data effectively and efficiently. Almost in every computer program data structures are used to maintain the data. for developing the system programs like compilers, data structures plays the major role. Some of the data structures are
  • Arrays
  • Stack
  • Queue
  • linked lists
  • Binary trees
  • Files

Write a C program with out using semicolon


The logic for this is tricky. Generally C language parse the code as expressions. Compiler checks for the valid expressions. If the expression is invalid , it will throw compilation error. It applies for the condition checking also. here comes the trick. see below example.

int main()
{
if(printf("world\n"))
{
//nothing
}
}

In the above code, it checks for the valid expression in if statement. It will check for the validity of the expresion and not the result/return value of the expression. So it will display the message. you can give any valid expression for condition check.


Result of the above code:

practice 1813> gcc nosemicolon.c
practice 1814> ./a.out
world
practice 1815>

What is free() in C?


free() frees the allocated memory space pointed to ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed.

void free(void *ptr);

char *ptr;
ptr = (char *)calloc(10,sizeof(char));
free(ptr);

memory leak occurs if you are not freeing the allocated memory.

What is the difference between malloc and calloc ?


The basic difference between malloc() and calloc() is, in malloc() allocated memory is un-initialized, values in the allocated memory is undefined. Where as in calloc() allocated meory is initialized to zero. malloc will take only one argument size as input and retuns void pointer and calloc() need two arguments one is for size and second one is for size of the each allocated block and returns void pointer. For initialising the allocated memory, it needs the size of the each block, becaus of this calloc() needs second argument, it will specify the size of the each block.

void *malloc(size_t size)

void *calloc(size_t nmemb, size_t size)

char *ptr,*ptr1;
ptr = (char *)malloc(10*sizeof(char));
ptr1 = (char *)calloc(10,sizeof(char));

What is calloc()?


calloc() allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is initialized to zero.

void *calloc(size_t nmemb, size_t size)

The calloc() returns void pointer on success, which can be assigned to any pointer variable by type casting. on failure it returns NULL.

char *ptr;
ptr = (char *)calloc(10,sizeof(char));

In the above code, declared char pointer ptr and dynamically allocated 10 bytes using calloc(). calloc will returns void pointer, ptr is a char pointer so type casting it to char pointer.

What is void pointer?


void pointers are pointers that can point to any data type. It can be used for any data type like int, char etc. In C language, type casting not required. But in C++, need to type cast it manually. Void pointer is also called Generic pointer.

void *vp; // it can be used for int, char or any data type
int *ip;
char *cp;
vp=(int*)ip; // vp as a integer pointer
vp=(char *)cp; // vp as a char pointer

Static Vs dynamic allocation in C


Memory allocation: This depends on the programming language that you are using. I am giving here for C programming language.

Static memory allocation: This allocation also called as compile time allocation, as allocation will happen at the time of compilation.Stack segment memory will be used for this allocation. There wont be any memory leak in this allocation.

Advantages:
  • No memory leaks
  • allocated memory is available till the end
  • No need of freeing the allocated memory, it will be freed automatically.
Disadvantage:
  • There will be some memory wastage.
  • Not efficient.
e.g : array's, global variables, auto, static variables


Dynamic memory allocation : This allocation is also called as run time memory allocation as allocation will happen dynamically basing on requirement. Heap segment will be used for this allocation. Need to allocate the required amount of memory and need to free the allocated memory with out fail. for allocation and freeing there are special functions malloc, calloc, free in C and new , delete in C++. If you not freeing the allocated memory, there is a chance for memory leak.

Advantages:
  • Very efficient.
  • Uses less memory

Disadvantage:
  • Need to free the allocated memory
  • Memory leaks
  • Application may fail in run time

e.g : linked list, binary trees etc.

What is malloc()?


The malloc() function allocates specified no. of bytes and returns a pointer to the allocated memory. The memory is not initialized. If specified size is zero, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().


void *malloc(size_t size)

The malloc() returns void pointer on success, which can be assigned to any pointer variable by type casting. on failure it returns NULL.

char *ptr;
ptr = (char *)malloc(10*sizeof(char));

In the above code, declared char pointer ptr and dynamically allocated 10 bytes using malloc(). malloc will returns void pointer, we need char pointer so type casting it into char pointer. And in the function call we multiplied the size with sizeof operator. this is for aligning the the no.of bytes for the data type basing on the machine.

What is memory leak?


Memory leak: As per Wikipedia memory leak is, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system.

In C language memory leak occurs in dynamic allocation only. Generally there are two possibilities to occur.

1. Allocating the memory using malloc() or calloc() and not freeing that allocated memory using free.

2. free ing the memory without allocation.


One basic rule for checking memory leak is that no. of malloc() functions shoule be equal to the no.of free() functions in the application. There are many tools to detect the memory leaks. In that wellknown tool is valgrind. In all unix machines we can find this tool. I am giving below sample result of a valgrind for the samle code.

main()
{
char *ptr = (char *)malloc(10 * sizeof(char));
//free(ptr); // memory leak , uncomment for no memory leak
}

Valgrind result for the above code:

Unix:~/practice 1801> valgrind a.out

==29043== Memcheck, a memory error detector
==29043== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==29043== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==29043== Command: a.out
==29043==
==29043==
==29043== HEAP SUMMARY:
==29043== in use at exit: 10 bytes in 1 blocks
==29043== total heap usage: 1 allocs, 0 frees, 10 bytes allocated
==29043==
==29043== LEAK SUMMARY:
==29043== definitely lost: 10 bytes in 1 blocks
==29043== indirectly lost: 0 bytes in 0 blocks
==29043== possibly lost: 0 bytes in 0 blocks
==29043== still reachable: 0 bytes in 0 blocks
==29043== suppressed: 0 bytes in 0 blocks
==29043== Rerun with --leak-check=full to see details of leaked memory
==29043==
==29043== For counts of detected and suppressed errors, rerun with: -v
==29043== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
Unix:~/practice 1802>


In the above result, red colored data clearly showing the leakage details. LEAK SUMMARY will be displayed only if any leak occurs in the application/program. And it will give the details about all lost data, In our example it is 10 bytes lost as we are not free'd the allocated data.


Popular Posts