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.

Monday, December 19, 2016

How to use Valgrind for debugging C/C++ program


Valgrind tool is used to for memory leaks, uninitialized memory, reading or writing to memory that has been freed, invalid access to memory(boundary conditions for the dynamic arrays), mismatched use of malloc/new/new[] with free/delete/delete[] , double free/delete.

How to use Valgrind:
>Compile the program with -g option (this option will add debugging symbols), so that we can see line numbers of the program when debugging

 $ g++ -o test -g test.cpp  

Tuesday, September 6, 2016

Dynamic memory allocator: new in C++

In c++ we will use new operator to allocate memory dynamically . In this post we will know how this process happens and what are the steps involved while using new. Basic syntax for new is
new [placemenet-params] typename;
This expression will allocate the memory available from the free store and returns the pointer to the object of type 'typename'. And in case of class, struct types it will allocate memory and intialise the object then retun the pointer to the object 'typename'.

Saturday, July 2, 2016

Object Slicing in C++ with example

What is Object Slicing? 
When an instance of derived class  is copied to base class object by value , part of members associated with derived object will be lost(sliced) . Here base class object discards the data related to the derived class because base class object don't have information about the derived members

When we copy derived obj by value to base obj,  the base class copy constructor /assignment operator will call (copy constructor will call at assigning object at the time of declaration (or) pass by value argument to function and assignment operator will call when assigning object after declarion), so base class don't have information about the derived members to copy.  This means the base copy/assignment will copy members related to base class only.

The following sample c++ code will explain the above description.

Wednesday, June 8, 2016

Some Useful My Sql Queries for beginners


My Sql is a popularly used Relational Database Management System.  Database is used store and retrieve data efficiently with the proven algorithms. Here i'm providing some sql commands which are useful for beginners in my sql queries.

Here information_schema is the default database comes with Mysql installation.

>To check the engine used for the table - mytable
SELECT TABLE_NAME, ENGINE FROM information_schema.TABLES WHERE TABLE_NAME='mytable' AND TABLE_SCHEMA='mydatabase';

Thursday, May 26, 2016

Maria DB Storage Engines and Alogorithms used for Indexing

Maria DB is a Open source database and is a replacement for My SQL data base after My Sql (Sun Micro Systems) has been acquired by Oracle.

Database can have multiple tables and each table will use one storage engine, and we can use different storage engines for different tables in the database.

In this article i'm discussing about the storage engines of Maria DB. There are many storage engines that supports Maria DB, and these are pluggable engines.

To see the available storage engines in maria db, execute the following query

MariaDB [(none)]> show storage engines;  (or)
MariaDB [(none)]> show engines;
And for all these storage differ from one another with the following properties..

Thursday, May 12, 2016

Qt C++ to Qml Communication using qmlRegisterUncreatableType()


In this article i will discuss about how to access the C++ class  enum types and attributes in qml file using Qt c++ qmlRegisterUncreatableType() template function.

qmlRegisterUncreatableType() will register the c++ class type (derived from QObject) as the non-instantiable type with QML type system. So we can not create object for the class in qml file, but we can use the properties ans enumerated types belongs to this class in qml file.

To access the enum values in qml , we have to make it available to meta-object system with the following macro, Otherwise we cannot access in qml file.
Q_ENUMS(enumType)

To Register the c++ type with qml type system
 qmlRegisterUncreatableType("ModuleName/uri", MajorVersion, MinorVersion, "QmlName", "message");

Here i'm providing the sample code to demonstrate the use of qmlRegisterUncreatableType() to access c++ class attributes and enum types.

Saturday, May 7, 2016

Bit Operations: Qt Example

In this post i'm going to show you some bit operations with &, |, <<, >>, ~ using Qt example. This example include operations like set a particular bit in the given number, clear bit, check bit is set or not and to check whether the number is even or odd.

Following demonstrates the psuedo code of the operations.

> To Set a bit in the given number : perform Betwise OR (|) operation with  1 left shift(<<) by index of the bit to set
     num = num | (1<<index);

>To clear a bit in the given number: perform Betwise AND (&) operation with the inverted(~) 1 left shift(<<) by index of the bit to clear
    num = num & ~(1<<index);

Tuesday, May 3, 2016

'Cannot find -lGL' error while building the Qt widget application in Linux OS?


Hi all,

Did any one get "Cannot find -lGL" error while building the Qt widget application in Ubuntu operating system? Qt installer provides compiler, debugger, make and other tools for the development. But when you want to develop Qt graphical based application it requires Open GL libraries.

Most of the Linux OS will not provide Open GL libraries as default. To continue building Qt graphical applications just install this libraries.

For Ubuntu use the following command

Friday, June 28, 2013

Anonymous Unions in C++

Unions in C++ are special type of classes. We can declare member functions and variables with in the union in c++ (all 'C' features of union remain same). 
But in the unions all the data members share the same memory location.

    Union members are public by default as like structures.

     Anonymous unions are the special type unions with the no name and so we can not create object for that union. All the member data in the anonymous unions share same memory location. We can directly access the these members without any dot operator with in the block where these unions declared. 

Monday, May 27, 2013

Qt QML Introduction and Simple Example Program



QML is declarative language used to develop user interface, is a part of the Qt Quick module. Qt Quick consists of set of technologies including Qml, C++ API's for integrating Qml with Qt application, Qt creator IDE, rum time support.
Qt Quick module comes with the Qt with 4.7 or later versions.

Qml we use elements to draw something on the screen(output) like text, image, rectangle etc.Every element in the qml is like a object. We cal also implement javascript code in side the qml file. Item is the base type for the all the elements.

To start a Qml Application we need to import Qt Quick module with version in the beginning of the every qml file, because the elements we are going to use included in this module. For example the following element displat a rectangle.
Import QtQuick 1.0
Rectangle {
    id: rect
    width: 300
    height: 300
    color: "red"
}

Friday, January 25, 2013

What is the sizeof array type when passed as a function argument?

Sizeof() operator is used to find out the no. of memory bytes occupied by any datatype i.e. it will calculate the size of the given datatype. So if we pass a variable called i of type int, it will give output as 4 bytes, or if we pass a array type say arr which contains declaration as int arr[10] , it will give 40 as output.

We generally use sizeof() operator on array type to find out the number of elements an array contain by dividing the sizeof array by oth element of array (or any element).. The following program will illustrate this

#include<stdio.h>
int main()
{
    int arr[10],s;
    s=sizeof(arr)/sizeof(arr[0]);
    printf("sizeof arr %d\n",sizeof(arr));
    printf("no. of elements of arr %d\n",s);
    return 0;
}

Here the problem is what is the size of the array type in function when we pass it as a argument. This is something different because when we pass array as an argument, the array type decays to pointer. So we can't calculate the no.of elements in the function. This is described by the following program.

Monday, December 31, 2012

Which algorithm is efficient for swapping?

Swapping of two numbers/characters can be done by different ways. Generally all people know swapping using a temporary variable. 
In this post i will tell you how to swap two variables in 3 different ways,  and which algorithm is efficient to swap the variables. 

Here all the below examples are shown in C code(executed in linux environment with gcc compiler).

Method 1:
  • Swapping using a temporary variable:

Friday, December 7, 2012

How to write a UDP socket program in Qt


We have seen how to write a simple UDP socket program in C (Linux) in the earlier post..

Now we are going to learn how to write a simple UDP socket program in Qt..

In the following example we used to send and receive data on localhost address.
And the readyRead() signal and slot is used whenever the data receives on the given socket (i.e. socket reday for read data), the control goes to slot method.
writeDatagram() and readDatagram() API's used for sending and receiving data on the given udp socket.

Before starting the Program to write, create a Project using following steps 
  • open Qt creator
  • Create Project
  • Select Other Project in Projects tab then select Qt Console Application, then click on choose...
  • Then give the Project name
  • And then click on Next, Finish in the following dialog boxes
  • Then open the .pro file and write QT += network 
  • To create the cpp file Right click on the project then choose Add new

Monday, November 26, 2012

Linux Shell scripting basics and Simple example to add two numbers

Shell scripting is a file which contains the list of commands for executing. What is Shell? Shell is special program or application provided for the user interaction.
There are different kinds of shells in Unix/Linux, they are
  • Sh: Bourne Shell
  • Csh: C Shell
  • Ksh: Korn Shell
  • Bash: Bourne again Shell.. etc
Some of the advantages of the shell scripting are,
  • Automation of tasks such as backups,log monitoring etc
  • To do repetition of of tasks
  • Save lots of time..
Unix/Linux Shell scripting also containg the functions, control statements,loops like other programming languages C, C++...

Monday, November 12, 2012

Signal handling in Linux using signal() call

signal() function in linux is used to sets of handler for the given signal number, the handler is any of SIG_DFL(default action) or SIG_IGN(ignore signal) or address of user defined function which we called signal handler

syntax:
         sighandler_t signal(int signum, sighandler_t handler);

the second parameter is the address of the signal handler function (function pointer), which has the following syntax

         typedef void (*sighandler_t)(int );

Here the parameter int represents the Signal number.

Here is the simple C program which describes the SIGINT Signal handling in linux

signal.c

#include<stdio.h>
#include<signal.h>

Thursday, November 8, 2012

gethostbyname example in C


gethostbyname() function will return the host details such as hostname, aliase names of the host,type of address, and length of host address of the given hostname.

This function will return the hostent (host entry) structure which contain the all the above details. h_addr_list[0]  field of “hostent” structure will contain struct in_addr equivalent of the host address.


Sysntax: 

struct hostent *gethostbyname(const char *name);

Here name is any valid hostname  (or) IPV4 address in standard dot notation (or) IPV6  address in colon or dot notation


Here is the simple C Program in Linux that illustrates the gethostbyname() function.

Saturday, November 3, 2012

UDP Client Server C Program

Hii all, in this Post you will learn how to write a simple UDP Socket Program in C in linux to send a message to the server and server will reply you.
Unlike TCP, UDP does not have connection establishment.So there is no connet() system call in client and accept() systemcall in server.

So the System calls in the server are

1.socket()
2.bind()
3.recvfrom()
4.sendto(
and I client the system calls are
1.socket()
2.sendto()
3.recvfrom()

The simple UDP Client-Server Program is as follows


udp_server.c