Leak Tracer vs valgrind for memory leak analysis of a C++ project


Attaching a large project to leak tracer is faster than valgrind.
How to use leaktracer and valgrind step by step:
A memory leaking program which would be used to check for memory leak using LeakTracer.
#include<iostream>
using namespace std;
#include<unistd.h>
int main()
{
char* name = new char[20];//allocates 20 bytes
//delete[] name;//Now leaks 20 byte
//sleep (30);
return 0;
} 
------------------------STEPS to use LeakTracer----------

STEP-0: Compile with -g flag to capture gdb debugging symbols.
    g++ -g leakProgram.cpp
    Here "a.out" would be my application in which I want check memory leak

STEP-1: run command "LeakCheck" with your application, here a.out
    /usr/bin/LeakCheck /home/admin/a.out

STEP-2: run command "leak-analyze" with your application and generated file leak.out
    /usr/bin/leak-analyze a.out /home/admin/leak.out

----------------------------Example----------------------------
Ubuntu:~/$ g++ -g leakProgram.cpp
Ubuntu:~/$ /usr/bin/LeakCheck /home/admin/a.out
Ubuntu:~/$ /usr/bin/leak-analyze a.out /home/admin/leak.out
Gathered 1 (1 unique) points of data.
Reading symbols from a.out...done.
(gdb)
#-- Leak: counted 1x / total Size: 20
0x80485c2 is in main() (leakProgram.cpp:6).
5    {
6    char* name = new char[20];//allocates 20 bytes but not freed.


--------------------STEPS to use Valigrind----------
Ubuntu:~$ valgrind --tool=memcheck --leak-check=yes ./a.out
==6829== Memcheck, a memory error detector
==6829== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==6829== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==6829== Command: ./a.out
==6829==
==6829==
==6829== HEAP SUMMARY:
==6829==     in use at exit: 20 bytes in 1 blocks
==6829==   total heap usage: 1 allocs, 0 frees, 20 bytes allocated
==6829==
==6829== 20 bytes in 1 blocks are definitely lost in loss record 1 of 1
==6829==    at 0x402ADFC: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==6829==    by 0x80485C1: main (leakProgram.cpp:6)
==6829==
==6829== LEAK SUMMARY:
==6829==    definitely lost: 20 bytes in 1 blocks
==6829==    indirectly lost: 0 bytes in 0 blocks
==6829==      possibly lost: 0 bytes in 0 blocks
==6829==    still reachable: 0 bytes in 0 blocks
==6829==         suppressed: 0 bytes in 0 blocks
==6829==
==6829== For counts of detected and suppressed errors, rerun with: -v
==6829== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

CMakeLists.txt and cmake interview questions

Common GDB Debugging Question

How to attach gdb with running process

Remote Debugging using gdb

How to debug multi threaded application using gdb

Advance debugging C/C++ code in GDB in Linux

You may also like:

  Singleton Design Pattern example in C++


 

CMakeLists.txt and cmake interview questions

 

 

How to attach gdb with running process

How to attach gdb with running process ?
gdb <PROCESS NAME> <PROCESS ID>
 we can grab the process id with ps command.
Suppose your program name is a.out
so command to get the process id would be?
ps -elf | grep a.out
usr1   4473  3529  0 16:42 pts/0    00:00:00 grep --color=auto a.out
here process name is a.out and process id is 4473
so command to attach the running process a.out with process id a.out would be
gdb a.out 4473
Note: You might require to execute as sudo user.

You may also like:

Remote Debugging using gdb

Q) How to do Remote Debugging using gdb?
1) On host machine Start a gdbserver and 2) Connect gdb from Host Machine to remote gdbserver
1) Start a gdbserver:
On Host Machine start gdbserver with application to debug on a specified IP and Port i.e.
gdbserver <IP>:<PORT> <APPLICATION>
e.g.
gdbserver 192.168.1.8:8082 Debug/Dummy
Output:
Process Debug/Dummy created; pid = 3523
Listening on port 8082
It will start the gdbserver for application “Dummy” on port 8082 and will wait for a host to connect to this on port 8082.

2.) Connect gdb from Host Machine to remote gdbserver

From the Host Machine start gdb and execute following command on gdb command prompt
target remote <TARGET MACHINE IP>:<GDBSERVER PORT>
eg
(gdb) target remote 192.168.1.8:8082
It will connect this gdb from Host Machine to remote gdbserver running on Target Machine. Now on Host Machine it will show a gdb command prompt.
output:
Remote debugging using 192.168.1.8:8082
warning: Could not load vsyscall page because no executable was specified
try using the "file" command first.
0x00007ffff7dd9cd0 in ?? ()
(gdb)
Now gdb from Host Machine is connected to target Machine’s gdbserver. Press “c” to continue debugging,
(gdb) c

CMakeLists.txt and cmake interview questions

How to debug multi threaded application using gdb

Q) How to debug a multi threaded application?
NOTE: "ulimit -c unlimited" command to set unlimited size for large core dump generation.
NOTE: "g++ thread1.cpp -g -lpthread" command to compile thread1.cpp file with pthread library.
NOTE: "break funcion_name or filename:line", "run","continue","step","list","print","attach -c core appNmae","bt", "thread apply all bt", "info thread", "thread thread id","bt","quit".
NOTE: step executes a function as a single instruction and continue stepinto the function definition of function.
Command to debug a core file core:
attach the core file and application that has dump the code and take the bt.
"gdb -c core ./a.out"

Then it will show function causing the core dump was called by which thread by seeing start_thread(arg=0xb6bedb40).
Here 0xb6bedb40 is the thread id.

Then run the commands: "info thread" to see the culprit thread "0xb6bedb40"'s stack id.
In this case culprit thread is "0xb6bedb40",whose thread stack id is 3.
So either we can switch to third thread by command "thread 3", and take bt of the third thread only by command "bt" or
we can take stack of all the threads by "thread apply all bt". and use the stack of the thread 3 only to debug or
In this case line at thread1.cpp:37 caused the crashed by thread 3 so we can take bt of "thread 3"
Detailed steps:
-----------------
(gdb) bt //STEP:1
#0  0x08048b3c in odd (o=0x0) at thread1.cpp:37
#1  0xb76f3f70 in start_thread (arg=0xb6bedb40) at pthread_create.c:312
#2  0xb754170e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129
(gdb) info thread //STEP:2
  Id   Target Id         Frame
  3    Thread 0xb73eeb40 (LWP 15708) 0xb7723424 in __kernel_vsyscall ()
  2    Thread 0xb73f0700 (LWP 15707) 0xb7723424 in __kernel_vsyscall ()
* 1    Thread 0xb6bedb40 (LWP 15709) 0x08048b3c in odd (o=0x0) at thread1.cpp:37
(gdb) thread 3 //STEP:4
[Switching to thread 3 (Thread 0xb73eeb40 (LWP 15708))]
#0  0xb7723424 in __kernel_vsyscall ()
(gdb) bt //STEP:5
#0  0xb7723424 in __kernel_vsyscall ()
#1  0xb76f7d4b in pthread_cond_wait@@GLIBC_2.3.2 () at ../nptl/sysdeps/unix/sysv/linux/i386/i686/../i486/pthread_cond_wait.S:187
#2  0x08048a3b in even (v=0x0) at thread1.cpp:17
#3  0xb76f3f70 in start_thread (arg=0xb73eeb40) at pthread_create.c:312
#4  0xb754170e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129
(gdb) thread apply all bt //STEP:5

Thread 3 (Thread 0xb73eeb40 (LWP 15708)):
#0  0xb7723424 in __kernel_vsyscall ()
#1  0xb76f7d4b in pthread_cond_wait@@GLIBC_2.3.2 () at ../nptl/sysdeps/unix/sysv/linux/i386/i686/../i486/pthread_cond_wait.S:187
#2  0x08048a3b in even (v=0x0) at thread1.cpp:17
#3  0xb76f3f70 in start_thread (arg=0xb73eeb40) at pthread_create.c:312
#4  0xb754170e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129

Thread 2 (Thread 0xb73f0700 (LWP 15707)):
#0  0xb7723424 in __kernel_vsyscall ()
#1  0xb76f5178 in pthread_join (threadid=3074353984, thread_return=0x0) at pthread_join.c:92
#2  0x08048c51 in main () at thread1.cpp:54

Thread 1 (Thread 0xb6bedb40 (LWP 15709)):
#0  0x08048b3c in odd (o=0x0) at thread1.cpp:37
#1  0xb76f3f70 in start_thread (arg=0xb6bedb40) at pthread_create.c:312
#2  0xb754170e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129



Q) How to skip 20 lines and show next 10 lines:
list +20,+10

if list shows lines upto 52 then list +20,+10
will displays 10 lines after the line from 72(52+20).
ie it display line 72 to 82

Q) Program using two threads to print odd and even. In each thread function I have knowngly introduced dived by zero error. Need to debug which thread is causing the divide by zero error first and dump core and optimize the code for that thread accordingly.
//Improved Example synchronized using mutex and conditional variable.
#include<iostream>
using namespace std;
#include<stdio.h>
int count=0;
int maxx=10;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* even(void *v)
{
    //cout<<"even thread"<<endl;
    while(count<maxx)
    {
        pthread_mutex_lock(&mutex);//lock before checking
        while((count%2)!=0)
        {
            pthread_cond_wait(&cond,&mutex);//wait until count becomes odd
            //it releases the mutex and it waits till condition cond is signaled as complete and mutex is available.
        }
    if(count==6){printf("%d",count/0);}
        cout<<"even "<<count++<<endl;
        pthread_mutex_unlock(&mutex);//release
        pthread_cond_signal(&cond);//signal to another thread
    }
    pthread_exit(0);//pthread_exit is called from the thread itself to terminate its execution (and return a result) early.
}
void* odd(void *o)
{
    while(count<maxx)
    {

        pthread_mutex_lock(&mutex);//lock before checking
        while((count%2)!=1)
        {
            pthread_cond_wait(&cond,&mutex);//wait until count becomes odd
        }
    if(count==5){printf("%d",count/0);}
        cout<<"odd "<<count++<<endl;
        pthread_mutex_unlock(&mutex);//release
        pthread_cond_signal(&cond);//signal to another thread
    }
    pthread_exit(0);
}
int main()
{
    pthread_t t1;
    pthread_t t2;

    pthread_mutex_init(&mutex, 0);
    pthread_cond_init(&cond, 0);

    pthread_create(&t1,NULL,&even,NULL);
    pthread_create(&t2,NULL,&odd,NULL);
    pthread_join(t1,0);
    pthread_join(t2,0);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    //pthread_join is called from another thread to wait for a thread to terminate and obtain its return value
    cout<<endl;
    return 0;
}
-----------------------------------------------
Q) Ho to debug multi-threading Applications with gdb debugger?
Compiling Multi-threaded Code using g++ with Debug Info
g++ -g --std=c++11 -pthread sample.cpp -o sample

Q)How to List all active threads?
“info threads”

Q)How to Check Stack trace of threads ?
In non multi threading applications there is only one thread i.e. main function. Therefore, to check the stacktrace we use command “bt”.
But in multi threading applications, as there are many threads and each threads has its own stack.
But “bt” command will display the stack trace of current active thread only. Now what if want to inspect stacktrace of all the threads at same point ?
To display the stack trace of all the threads use following command
(gdb) thread apply all bt

//output would be

Thread 3 (Thread 0xb74a8b40 (LWP 4335)):

#0  __GI___nptl_death_event () at events.c:31
#1  0xb7faf104 in start_thread (arg=0xb74a8b40) at pthread_create.c:363
#2  0xb7dfc70e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129

Thread 1 (Thread 0xb7cab700 (LWP 4330)):

#0  main () at threadOddEven.cpp:17
(gdb)


Q) How to Switch between threads while debugging?
(gdb) thread <Thread Number>
(gdb) thread 2
(gdb) thread 1

CMakeLists.txt and cmake interview questions

C program to find frequency of each character in a string

//C/Cpp/C++ program to find frequency of each characters in a string
//C/Cpp/C++ program to find non repeating characters in a string
//C/Cpp/C++ program to find repeating characters in a string
//C/Cpp/C++ program to output a1b2c3d4 when input is "abbcccdddd"
/*Idea is to keep count of each characters
'a'=count[0] occurs how many times 0,1,2.3..
'b'=count[1] occurs how many times 0,1,2,3..
.
.
'z'=count[25] occurs how many times 0,1,2,3....
*/
#include<iostream>
using namespace std;
#include<stdio.h>
#include<string.h>
int main()
{
char a='a';
cout<<"a-97="<<a-97<<endl;//0
cout<<"'a'-97="<<'a'-97<<endl;//0

cout<<"manin()\n";
char arr[]="abbccc";
int count[26];
int i;
for(i=0;i<26;i++)
count[i]=0;

i=0;
//while(arr[i]!='\0')
for(i=0;i<strlen(arr);i++)
{
printf("arr[i]=%c arr[i]-97=%d count[arr[i]-97]]=%d\n",arr[i],arr[i]-97,count[arr[i]-97]);
if(arr[i]>='a' && arr[i]<='z')
    count[arr[i]-97]=count[arr[i]-97]+1;//count[arr[i]-97]++;
if(arr[i]>='A' && arr[i]<='Z')
    count[arr[i]-65]=count[arr[i]-65]+1;//count[arr[i]-65]++;
//i++;
}

printf("\nPrinting frequency of each character:\n");
for(i=0;i<25;i++)
{
if(count[i]>0)//characters which occurs atleast once
printf(" %c%d",i+97,count[i]);//a1b2c3
}
printf("\nPrinting repeated character:\n");
for(i=0;i<25;i++)
{
if(count[i]>1)//characters which occurs atleast 2
printf(" %c%d",i+97,count[i]);//a1b2c3
}
printf("\nPrinting character which are unique or none repeating characters:\n");
for(i=0;i<25;i++)
{
if(count[i]==1)//characters which occurs only once or uniquely
printf(" %c%d",i+97,count[i]);//a1b2c3
}


printf("\n");
return 0;
}
/*
a-97=0
'a'-97=0
manin()
arr[i]=a arr[i]-97=0 count[arr[i]-97]]=0
arr[i]=b arr[i]-97=1 count[arr[i]-97]]=0
arr[i]=b arr[i]-97=1 count[arr[i]-97]]=1
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=0
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=1
arr[i]=c arr[i]-97=2 count[arr[i]-97]]=2

Printing frequency of each character:
a1 b2 c3
Printing repeated character:
b2 c3
Printing character which are unique or none repeating characters:
a1
http://www.codeforwin.in/2015/04/c-program-to-calculate-the-frequency-of-each-character-in-a-line.html
*/

C program to convert Decimal to binary, binary to decimal, reverse a number, pallindrom check

Decimal to Binary
//C program to convert decimal to binary
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num;
cout<<"Enter a decimal number:";//13
cin>>num;
int n,r,i=1;
unsigned long s=0;
n=num;
while(n>0)
{
r=n%2;//13%2=1 //6%2=0 //3%2=1 //1%2=1//
n=n/2;//13/2=6 //6/2=3 //3/2=1 //1/2=0
s=s+r*i;//0+1*1=1 //1+0*10=1 //1+1*100=101 //101+1*1000=1101
i=i*10;//1*10=10//10*10=100 //100*10=1000 //10000
cout<<"r="<<r<<" n="<<n<<" s="<<s<<" i="<<i<<endl;
}
cout<<"Decimal number "<<num<<" in binary is: "<<s<<endl;//1101

return 0;
}
/*
Enter a decimal number:13
r=1 n=6 s=1 i=10
r=0 n=3 s=1 i=100
r=1 n=1 s=101 i=1000
r=1 n=0 s=1101 i=10000
Decimal number 13in binary is: 1101
*/
//Binary to Decimal
#include<iostream>
using namespace std;
#include<math.h>

int main()
{
cout<<"manin()\n";
int num;
cout<<"Enter a binary number:";//1101=13
cin>>num;
int n,r,i=0;
unsigned long s=0;
n=num;
while(n>0)
{
r=n%10;//
n=n/10;//
s=s+r*pow(2,i);//
++i;
cout<<"r="<<r<<" n="<<n<<" s="<<s<<" i="<<i<<endl;
}
cout<<"binary number "<<num<<" in Decimal is: "<<s<<endl;//1101

return 0;
}
/*
manin()
Enter a binary number:1101
r=1 n=110 s=1 i=1
r=0 n=11 s=1 i=2
r=1 n=1 s=5 i=3
r=1 n=0 s=13 i=4
binary number 1101 in Decimal is: 13
*/
//Sum of digits of a numbers
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1//1/10=0
sum=sum+r;//4//4+3//4+3+2//4+3+2+1=10
}
cout<<"sum of "<<num<<" is "<<sum<<endl;//10
return 0;
}
//Reverse Number
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1// 1/10=0
sum=sum*10+r;//0*10+4=4//4*10+3=40+3=43//43*10+2=430+2=432//432*10+1=4320+1=4321
}
cout<<"sum of "<<num<<" is "<<sum<<endl;//4321
return 0;
}
//Pallindrom number
#include<iostream>
using namespace std;

int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1// 1/10=0
sum=sum*10+r;//0*10+4=4//4*10+3=40+3=43//43*10+2=430+2=432//432*10+1=4320+1=4321
}
if(num==sum)
{
cout<<"Its a pallindrom "<<num<<" is equal to "<<sum<<endl;//4321
}
else
{
cout<<"Not a pallindrom.\n";
}
return 0;
}
//Reversing String
#include<iostream>
using namespace std;
#include<string.h>
void strRev(char *arr);

int main()
{
cout<<"manin()\n";
char arr[]="Hello";
///*
int result;
char *end;
char *start;
end=arr;
start=arr;
int l,i;
char t;
l=strlen(arr);
for(i=0;i<l-1;i++)
end++;
for(i=0;i<=l/2;i++)
{
t=*start;
*start=*end;
*end=t;
start++;
end--;
}
//*/
cout<<"reversed string is:"<<arr<<endl;
cout<<"\nAgain reversing using function:\n";
strRev(arr);
cout<<"arr is now again: "<<arr<<endl;
//cout<<"Reverse string is: "<<strRev(arr)<<endl;
return 0;
}
void strRev(char *arr)
{
char *start=arr;
char *end=arr;
int l,i;
char t;
l=strlen(arr);
for(i=0;i<l-1;i++)
end++;
for(i=0;i<l/2;i++)
{
t=*start;
*start=*end;
*end=t;
start++;
end--;
}
}
/*
manin()
reversed string is:olleH
Again reversing using function:
arr is now again: Hello
*/

C program to merge two sorted arrays. Array Union

//C/C++/C Plus Plus program to merge two sorted arrays
//C/C++/C Plus Plus program to find union of two sorted arrays
#include<iostream>
using namespace std;
#include<stdio.h>

int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5,7,8,9};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
{
printf("%d",arr1[i]);
i++;
}
else if(arr2[j]<arr1[i])
{
printf("%d",arr2[j]);
j++;
}
else //arr[i]==arr[j]
{
printf("%d",arr2[j]);
i++;
j++;
}
}
while(i<n1)
printf("%d",arr1[i++]);
while(j<n2)
printf("%d",arr2[j++]);

cout<<endl;
}
//output
//12345789

C program to find common numbers in two sorted arrays. Array intersection

//C/C++/C Plus Plus program to find common numbers in two sorted arrays
//C/C++/C Plus Plus program to find intersection of two sorted arrays
//C/C++/C Plus Plus program to find common elements of two sorted arrays
#include<iostream>
using namespace std;

int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
i++;
else if(arr2[j]<arr1[i])
j++;
else //arr[i]==arr[j]
{
cout<<"common elements are:"<<arr2[j]<<endl;
i++;
j++;
}

}
}

C Program for sorting an array using Bubble Sort and Insertion Sort

#include<iostream>
using namespace std;
int main()
{
cout<<"manin()\n";
int arr[20],n,i,j,t;
cout<<"Enter the number of elements in array:"<<endl;
cin>>n;
cout<<"Enter the elements:";
for(i=0;i<n;i++)
cin>>arr[i];

cout<<"Entered the elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";

/*
cout<<"Bubble sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
cout<<n-i-1<<" "<<j<<" "<<j+1<<" "<<endl;
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
*/
//OR
/*
Selection sort: By first scanning the entire list before locating the exact pair of numbers to swap, only two writes to memory are performed by Selection Sort for each O(n) scan,whereas
Bubble Sort does writes on each and every comparison. So, Bubble Sort does O(n^2) writes. while selection sort does O(n) writes to mwmory.
*/
cout<<"\nSelection sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)//mind n-1
{
for(j=i+1;j<n;j++) //mind n
{
if(arr[i]>arr[j])
{
cout<<n<<" "<<i<<" "<<j<<" "<<endl;
t=arr[j];
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}


cout<<"Sorted array elements are:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";

cout<<endl;
return 0;
}
/*
//Selection Sort:
manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
4 1 2
4 2 3
4 3 4
4 4 5
3 2 3
3 3 4
3 4 5
2 3 4
2 4 5
1 4 5
Sorted array elements are:
1 2 3 4 5

//Bubble sort

manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
5 0 1
5 0 2
5 0 3
5 0 4
5 1 2
5 1 3
5 1 4
5 2 3
5 2 4
5 3 4
Sorted array elements are:
1 2 3 4 5
*/
/*
In Bubble sort , at every iteration you find a largest number and push it to bottom (Bubble out larger number)
In Insertion sort you have two regions one sorted and another unsorted.
At Every Iteration you pick up an element from unsorted region and insert at proper location in Sorted region.

Insertion Sort and Bubble sort both have Worst Case O(N^2).
But if the array is mostly sorted Insertion Sort will perform better
For both insertion and bubble sort worst case is O(n^2)
*/

C++ STL interview questions

Q) What do you mean by " every iterator and reference after the point of resize/erase is invalidated "?(except when erased member is first or last member of container)
Q) What is the difference between capacity and size in vector container in STL?
Q) If initially size allocated to vector is 10. What would be the capacity of the vector? Will it be doubled?
Q) Write a program to demonstrate vector's algorithms ?
Q) Write a program to demonstrate map and multi map's algorithms?
Q) Write a program to demonstrate set and multi set's operations ?
Q) What is the return type of find algorithm in STL container?
Q) Write a program to find the  first match of pattern in given strings and its position? Use vector of strings?
Q) Write a program to find all matches of pattern in given strings and its position? Use vector of strings?
Q) What is the difference between array an vector?
Q) What is the difference between vector, list, set and map?
Q) Why vectors are thread safe?

Q) What do you mean by " every iterator and reference after the point of resize/erase is invalidated "?
Invalidation  in vector means pointing out side of range of vector or pointing to altogether different value.
Insertion consequence in a vector:
i)All iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated.
ii)Erase consequences in vector: 
Every iterator and reference after the point of erase is invalidated.
iii)Resize effect in vector:
As per insertion and erase.
 example code of vector invalidation in c++ STL vector:
#include<iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
    int arr[] = { 10, 20, 30 };

    std::vector<int> vec(arr, arr + 3);
    // vector contains 1, 2, 3
        //size 3 and capasity 4

    std::vector<int>::iterator i = vec.begin();
    cout <<"*i="<< *i << endl; // prints 10
    int &ref = *i;
    cout <<"ref="<<ref << endl; // prints 10

    vec.resize(5, 100);
//vector now contains 1, 2, 3, 100, 100
//now capasity is 8 > size 5

    // WRONG! might work, crash or invalid result
    cout <<"*i=="<< *i << endl; // prints 0

    // WRONG! invalid reference
    cout <<"ref=="<<ref << endl; // prints 0

   return 0;
}

STL Map all operations example - map all algorithms

What is a map?
A map is an associative container which stores elements in key-value pair.
By default elements are stored in sorted fashion in ascending order of key. Binary search tree is internal data structure to implement maps.
How to insert in a map?
i) using 'insert" algorithm or
ii)using [key]=value style.
What is the difference between above two ways of insertion in maps?
What happens when a value is inserted in a map    ?
It depends on what algorithm has been used to insert.
i)If "insert.(pair<keyType,valuType>(key,value))" is used then value is simply gets ignored if that key already exists.
ii)If [key]=value is used then new value gets replaced if that key already exists.
iii)If at(key)=value is used then also new value is update to key.
How to delete using key?
By "find" and "erase" algorithm.
C++ MAP STL example code:
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
map<int,string> m;//actually <string, int> example is more used
m.insert(pair<int,string>(1,"Ram"));
m.insert(pair<int,string>(4,"Ram"));
m.insert(pair<int,string>(8,"Ram"));
m.insert(pair<int,string>(3,"Ram"));
m.insert(pair<int,string>(5,"Ram"));
m.insert(pair<int,string>(500,"Ram"));
m.insert(pair<int,string>(50,"Ram"));
m.insert(pair<int,string>(100,"Ram"));
m[1000]="Supreme";


cout<<"map is:"<<endl;
map<int,string>::iterator itr;
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;//sorted keys

cout<<"Erase all with key 4"<<endl;
int del=m.erase(4);
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"erase all less than key 8"<<endl;
m.erase(m.begin(),m.find(8));
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

//find(const g) – Returns an iterator to the element with key value ‘g’ in the map if found, else returns the iterator to end
cout<<"Finding key 100 and deleting it."<<endl;
map<int,string>::iterator itr2=m.begin();
itr2=m.find(100);
if(itr2!=m.end())
{
cout<<"100 found"<<endl;
m.erase(itr2);
//m.at(100) = "NewValue";
}
else
{
cout<<"100 not found"<<endl;
}
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Deleting key 50"<<endl;
m.erase(50);
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Inserting using at(key)"<<endl;
m.at(8) = "Raheem";
m.at(500) = "Jesus";
//m.at(100) = "God";//out of range when tries to insert at a key which does not exists
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Find(key)->second display."<<endl;
cout << "8 => " << m.find(8)->second<<endl;
cout << "500 => " << m.find(500)->second<<endl;
//cout << "500 => " << m.find(100)->second<<endl;//empty

cout<<endl;
return 0;
}
Example 2:
What is the difference between two different ways of inserting into a map?
What will happen if duplicate values are inserted in a map?
i) inserting using algorthm"insert" : Does nothing. Key holds the old value.
ii) inserting using [] : update the key with new value.
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
cout<<""<<endl;
map<string,int> m;
//In map values are inserted in asending order of keys.
m.insert(pair<string,int> ("Manoj",5));
m.insert(make_pair("Sony",2));
m.insert(make_pair("Aditi",3));
//insert resturns false if same key is inserted again.
//Nothing happens if we insert duplicatge key.
m.insert(make_pair("Aditi",4));//Not inserted as key Aditi already exists.
m.insert(make_pair("Aditi",5));//Not inserted as key Aditi already exists.
//Different keys can have the same value as another key's value.
m.insert(make_pair("Biswa",3));//Biswa inserted after Aditi.

map<string,int>::iterator itr=m.begin();
while(itr!=m.end())
{
cout<<itr->first<<" "<<itr->second<<endl;
itr++;
}
/*
Aditi 3
Biswa 3
Manoj 1
Sony 2
*/
cout<<"Another map to show second way of inserting elements:\n";
map<string,int> m2;
m2.insert(make_pair("AAA",1));
m2.at("AAA")=300;//now value of key AAA is also gets updated
m2["BBB"]=2;//now value of key BBB is 2
m2["BBB"]=3;//now value of key BBB is 3
m2["BBB"]=4000;//now value of key BBB is 4000
map<string,int>::iterator itr2=m2.begin();
while(itr2!=m2.end())
{
cout<<itr2->first<<" "<<itr2->second<<endl;
itr2++;
}
/*
AAA300
BBB 4000
*/
return 0
 }
Multi Map example to hold duplicate keys:
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
cout<<""<<endl;
multimap<string,int> m;
//In map values are inserted in asending order of keys.
m.insert(pair<string,int> ("Manoj",5));
m.insert(make_pair("Sony",2));
m.insert(make_pair("Aditi",3));
m.insert(make_pair("Aditi",4));//Another Aditi with new value 4
m.insert(make_pair("Aditi",5));//Another Aditi with new value 5
m.insert(make_pair("Biswa",3));//Biswa inserted after Aditi.

multimap<string,int>::iterator itr=m.begin();
while(itr!=m.end())
{
cout<<itr->first<<" "<<itr->second<<endl;
itr++;
}
/*
Aditi 3
Aditi 4
Aditi 5
Biswa 3
Manoj 5
Sony 2
*/
cout<<"---map example to find a key"<<endl;
cout<<"---find returns iterator to the found keys"<<endl;
cout<<"---find returns false so garbage value"<<endl;
itr=m.begin();
cout<<"m.find(Aditi)="<<m.find("Aditi")->second<<endl;//3//first match only.
cout<<"m.find(Manoj)="<<m.find("Manoj")->second<<endl;//5
cout<<"m.find(Sahu)="<<m.find("Sahu")->second<<endl;//garbage

itr=m.begin();
if(m.find("Aditiii")!=m.end())
cout<<itr->first<<" found and value is "<<itr->second<<endl;
else
cout<<"Not found"<<endl;

return 0;
}
/*
Aditi 3
Aditi 4
Aditi 5
Biswa 3
Manoj 5
Sony 2
---map example to find a key
---find returns iterator to the found keys
---find returns false so garbage value
m.find(Aditi)=3
m.find(Manoj)=5
m.find(Sahu)=223444160
Not found
*/ 
In multi map "find" return the value of first key only.
How to find all the values associated with duplicate key?
Using the algorithm equal_range("key").
Count can be taken by algorithm "distance" 

What are QML FAQ in interviews?

Q) What is Qml ?
QML is the name of the language (just like C++, which is another language...)
QML stands for Qt Meta Language or Qt Modelling Language is a user interface markup language.
Q) How to call c++ call from QML?
QML call C + + methods with the Qt meta-object system. Like below:
onClicked: parent.color = parent.randomColor ()

Q) What are Four ways of integreting C++ with Qml?
Subclassing QQuickItem: QQuickItem allows you to write your own visual and non-visual QML items using C++.
Registering C++ types with QML: C++ classes can be registered with the QML type system, allowing them to be instantiated as QML types.
Registering Context Properties: QObjects can be registered with the QML context, allowing their properties to be directly accessed.
Accessing QML objects through the QML object tree: All QML objects reside in a tree hierarchy and can be accessed via the root of the tree.
http://www.ics.com/blog/multilayered-architecture-qt-quick

Q) How to call a C++ function from a qml?
Through setcontext property.
Note
Loading a main.qml with a simple Item as the root type through the QmlApplicationEngine will not show anything on your display, as it requires a window to manage a surface for rendering. The engine is capable of loading qml code which does not contain any user interface (e.g plain objects). Because of this it does not create a window for you by default.
The qmlscene or the new qml runtime will internally first check if the main qml file contains a window as a root item and if not create one for you and set the root item as a child to the newly created window.

Q)What is Q_INVOKABLE?
Add callable methods using Q_INVOKABLE or Qt slots, and connect to Qt signals with an onSignal syntax

Q)How to call a QML function from c++?
QML functions can be called from C++ and vice-versa.
All QML functions are exposed to the meta-object system and can be called usingQMetaObject::invokeMethod(). Here is a C++ application that uses this to call a QML function:
// MyItem.qml
import QtQuick 1.0
Item {
    function myQmlFunction(msg) {
        console.log("Got message:", msg)
        return "some return value"
    }
}
// main.cpp
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, "MyItem.qml");
QObject *object = component.create();
QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
        Q_RETURN_ARG(QVariant, returnedValue),
        Q_ARG(QVariant, msg));
qDebug() << "QML function returned:" << returnedValue.toString();
delete object;

Q)How to call a C++ function from QML ?
A C++ function can be called from a qml using set contextpropery in c++.
http://doc.qt.io/qt-4.8/qtbinding.html
All QML signals are automatically available to C++, and can be connected to using QObject::connect() like any ordinary Qt C++ signal.
The signal is sent to QML, and the slot is invoked from QML.
There are different ways to send signals from C++ to QML and back. In this article, we show how to do this by embedding a C++ class directly into QML. This has the advantage that no Qt::connect connections need to be set-up manually.
In our example, we have a Receiver class that is implemented in C++.
This class defines a signal sendToQml and a slot receiveFromQml.
 Both have an integer parameter.
The signal is sent to QML, and the slot is invoked from QML.
Example:
//signal_slot.pro
TEMPLATE = app
QT += qml quick
#export QT_SELECT=5
SOURCES += main.cpp \
    receiver.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Default rules for deployment.
include(deployment.pri)
HEADERS += \
    receiver.h
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "receiver.h"
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    Receiver receiver;
    QQmlContext* ctx = engine.rootContext();
    ctx->setContextProperty("receiver", &receiver);
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
    receiver.sendToQml(43);
    //QDeclarativeView view;
    //view.rootContext()->setContextProperty("_EBSCModel",m_EBSCDtcDataModel);
    //sourcePath = "qrc:///DTC/qml/ITSDTC.qml";
    //view.setSource(QUrl(sourcePath));
    return app.exec();
}
//receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H
#include <QObject>
class Receiver : public QObject
{
    Q_OBJECT
public:
    explicit Receiver(QObject *parent = 0);
signals:
    void sendToQml(int count);
public slots:
    void receiveFromQml(int count);
};
#endif // RECEIVER_H
//receiver.cpp
#include "receiver.h"
#include <QDebug>
Receiver::Receiver(QObject *parent) :
   QObject(parent)
{
}

void Receiver::receiveFromQml(int count) {
    qDebug() << "Received in C++ from QML:" << count;
}
//main.qml
import QtQuick 2.2
import QtQuick.Window 2.1
Window {
    id: test
    visible: true
    width: 200
    height: 50
    Connections {
        target: receiver
        onSendToQml: {
            console.log("Received in QML from C++: " + count)
        }
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            receiver.receiveFromQml(42);
        }
    }

    Text {
        text: qsTr("Press me to send a signal to C++")
        anchors.centerIn: parent
    }
}

Signal and Slot Interview Questions

Q) Where is the body of the signals?
Signals are just simple functions, whose body is generated by moc. They are just calling QMetaObject::activate, with an array of pointers to arguments on the stack. Here is the code of a signal, as generated by moc.
Q) What is the need of proxy and adapater?

STL Vector example in C++ in Linux all operations

//Vector is a STL container. Vector is template type container, which can store any type of element by providing type in template arguments. Vector size expanded to double or shrinks dynamically at run time. Just like array memory is allocated contagiously but unlike array it is stored in heap. 
//vector is should be preferred as compared to dynamic array because
//1.memory is automatically freed in case of vector on destruction
//2.vector is implemented internally as dynamic array in heap which
//shrinks and grows automatically so no wastage of memory
//3. It is fast as elements can be accessed randomly by index just like arrays.
For understanding:
No of elt  size  capasity
0              0       0
1              1       1 
2              2       2
3              3       4
4              4       4
5              5       8
6              6       8
7              7       8
8              8       8 
9              9       16
10           10      16
17            17     32 
Example:       
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
int main()
{
vector<string> myvector;
cout<<"-----"<<"Inserting at end using pushback is efficient in vector as no shift:"<<endl;
myvector.push_back("cccc");
myvector.push_back("bbbb");
myvector.push_back("eeee");
myvector.push_back("aaaa");
myvector.push_back("dddd");
cout<<"-----"<<"Size of the vector is:"<<myvector.size()<<endl;

cout<<"-----"<<"Traversing vector with iterator:"<<endl;
vector<string>::iterator it;
for(it=myvector.begin();it!=myvector.end();it++)
cout<<*it<<" ";//mind the syntax to display//cccc bbbb eeee aaaa dddd

cout<<"\n----"<<"Traversing vector with index subscripts:"<<endl;
for(int i=0;i<myvector.size();i++)
cout<<myvector[i];//mind the syntax to display//cccc bbbb eeee aaaa dddd

cout<<"\n-------"<<"Sorting vector elements in ascending order:"<<endl;
sort(myvector.begin(),myvector.end());
for(it=myvector.begin();it!=myvector.end();it++)
cout<<*it<<" ";//aaaa bbbb cccc dddd eeee

cout<<"\n------------"<<"Finding a string in a vector of strings:"<<endl;
int pos;string elt="bbbb";
pos=find(myvector.begin(),myvector.end(),elt)-myvector.begin();
if(pos<myvector.size())//
cout<<"bbbb found at index:"<<pos<<endl;//bbbb at 1st index
else
cout<<"Not found"<<endl;

cout<<"------------"<<"Vector before erasing is:"<<endl;
for(int i=0;i<myvector.size();i++)
cout<<myvector.at(i);//aaaa bbbb cccc dddd eeee

cout<<"\n------------"<<"Erasing 1st index element ie bbbb of vector"<<endl;
myvector.erase(myvector.begin()+1);//deleting 1st index leaving 0th index elt
cout<<"Now vector is:";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//aaaa cccc dddd eeee

cout<<"\n------------"<<"Erasing first 2 elements:"<<endl;
myvector.erase(myvector.begin(), myvector.begin()+2);//2 elements and not 2 index
cout<<"Now vector is:";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//dddd eeee

cout<<"\n------------"<<"clear deletes all the elts of a vector"<<endl;
//Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
myvector.clear();
for(int i=0;i<myvector.size();i++)
cout<<myvector[i];//empty

cout<<"------------"<<"Inserting method 2 in vector"<<endl;
myvector.push_back("ffff");
myvector.push_back("gggg");

cout<<"------------"<<"pop_back in vector to delete from last"<<endl;
while(!myvector.empty())
{
cout<<myvector.back();//gggg ffff
myvector.pop_back();
}//vector is empty now
cout<<"\nInserting after 0th elt";
vector<string>::iterator itr2=myvector.begin();
myvector.insert(itr2,"bbbb");
myvector.insert(itr2,"pppp");
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//pppp bbbb

cout<<"\nInserting after nth elt";
vector<string>::iterator itr22=myvector.begin();
myvector.insert(itr22+1,"hhhh");//insert hhhh after pppp
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//pppp hhhh bbbb

cout<<"\n------------"<<"Finding other way:"<<endl;
vector<string>::iterator itr;
itr=find(myvector.begin(),myvector.end(),"pppp");
if(itr!=myvector.end())
{
cout<<"pppp found at position:"<<itr-myvector.begin()<<endl;//1
//deleting found element as
myvector.erase(itr);
}
else
{
cout<<"Not found"<<endl;
}
cout<<"After deleting pppp vector becomes:::\n";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];// hhhh bbbb

cout<<"\n------------"<<"Reverse a vecotr:"<<endl;
reverse(myvector.begin(),myvector.end());
for(int i=0;i<myvector.size();i++)
cout<<myvector[i]<<" ";//bbbb hhhh pppp

cout<<"\n------------"<<"insert repeated values"<<endl;
//exchanges elements of vectors even difference in sizes
vector<int> vec1 (3,100);   // three ints with a value of 100
vector<int> vec2 (5,200);   // five ints with a value of 200
vec1.swap(vec2);
for(int i=0;i<vec1.size();i++)
cout<<vec1[i]<<" ";//becomes 200 200 200 200 200

cout<<"\n------------"<<"Delete all occurence of an element from vector"<<endl;
vec1.erase(remove(vec1.begin(), vec1.end(), 200), vec1.end());
for(int i=0;i<vec1.size();i++)
cout<<vec1[i]<<" ";//becomes 200 200 200 200 200

cout<<"\n-------------"<<"Finding and deleting a particular element in a vector."<<endl;
//vector<int> vect3{20,30,40,111,111,11,60};//need to compile with -std=c++11
vector<int> vect3;
vect3.push_back(20);
vect3.push_back(30);
vect3.push_back(40);
vect3.push_back(111);
vect3.push_back(111);
vect3.push_back(11);
vect3.push_back(60);
int count=0;
for( vector<int>::iterator iter = vect3.begin(); iter != vect3.end(); ++iter )
{
count++;
    if( *iter == 111 )
    {
cout<<"111 found at: "<<count<<" and "<<vect3.at(count);
        vect3.erase( iter );
        break;
    }
}
cout<<"\nNow vector is:"<<endl;
for(int i=0;i<vect3.size();i++)
cout<<vect3[i]<<" ";//becomes 20 30 40 111 11 60

cout<<"\n----Find and replace in a vector of integers"<<endl;
int myints[] = { 11, 22, 33, 33, 11, 11, 22, 44,55,66 };
vector<int> myvector2 (myints, myints+10);            // 11 22 33 33 11 11 22 44 55 66
replace (myvector2.begin(), myvector2.end(), 22, 222); // 11 222 33 33 11 11 222 44 55 66

cout << "myvector2 contains:";
for (vector<int>::iterator it=myvector2.begin(); it!=myvector2.end(); ++it)
cout <<" "<< *it;//10 99 30 30 99 10 10 99

cout<<endl;
return 0;
}
/*
OUTPUT:
------------Inserting at end using pushback is efficient in vector as no shift:
------------Size of the vector is:5
------------Traversing vector with iterator:
cccc bbbb eeee aaaa dddd
------------Traversing vector with index subscripts:
ccccbbbbeeeeaaaadddd
------------Sorting vector elements in ascending order:
aaaa bbbb cccc dddd eeee
------------Finding a string in a vector of strings:
bbbb found at index:1
------------Vector before erasing is:
aaaabbbbccccddddeeee
------------Erasing 1st index element ie bbbb of vector
Now vector is: aaaa cccc dddd eeee
------------Erasing first 2 elements:
Now vector is: dddd eeee
------------clear deletes all the elts of a vector
------------Inserting method 2 in vector
------------pop_back in vector to delete from last
ggggffff
Inserting after 0th elt pppp bbbb
Inserting after nth elt pppp hhhh bbbb
------------Finding other way:
pppp found at position:0
After deleting pppp vector becomes:::
 hhhh bbbb
------------Reverse a vecotr:
bbbb hhhh
------------insert repeated values
200 200 200 200 200
------------Delete all occurence of an element from vector

-------------Finding and deleting a particular element in a vector.
111 found at: 4 and 111
Now vector is:
20 30 40 111 11 60

*/
/*Vector is internally implemented as dynamically allocated array.eg. if size is not know then int *p = new in[size].http://www.cplusplus.com/doc/tutorial/dynamic/ Non dynamic array example is int array[SIZE];wastage of unused memory. In dynamic array only pointer to array is static. So vector is used for efficient memory allocation when insert is at last scenarios.
As the vectors use an array as their underlying storage, inserting elements in positions other than the vector end causes the container to relocate all the elements that were after position to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).*/

Qt example for displaying text from line edit to label on button click using signal and slots

//connectButtonClose.pro
#-------------------------------------------------
# Project created by QtCreator
#-------------------------------------------------
QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = connectButtonClose
TEMPLATE = app
SOURCES += main.cpp\
        mainwindow.cpp
HEADERS  += mainwindow.h
FORMS    += mainwindow.ui
//---------------
//main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
   // MainWindow w;
   // w.show();
MainWindow *w = new MainWindow;
w->setUI();
    return a.exec();
}
//-------------
//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QDebug>
#include <QLineEdit>
#include <QLabel>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<endl;
    ui->setupUi(this);

//    qpb =new QPushButton("HitMe");
//    hl = new QHBoxLayout;
//    le = new QLineEdit();
//    label1 =new QLabel;
//    hl->addWidget(le);
//    hl->addWidget(qpb);
//    hl->addWidget(label1);

//    myWidget = new QWidget;
//    myWidget->setLayout(hl);
//    myWidget->show();
//    QObject::connect(qpb,SIGNAL(clicked()),this,SLOT(slotCalled()));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete qpb;
    delete hl;
    delete label1;
}
void MainWindow::setUI()
{
    qpb =new QPushButton("HitMe");
    hl = new QHBoxLayout;
    le = new QLineEdit();
    label1 =new QLabel;
    label2 =new QLabel;
    hl->addWidget(le);
    hl->addWidget(qpb);
    hl->addWidget(label1);
    hl->addWidget(label1);

    myWidget = new QWidget;
    myWidget->setLayout(hl);
    myWidget->show();

    QObject::connect(qpb,SIGNAL(clicked()),this,SLOT(slotCalled()));
    //QObject::connect(qpb,SIGNAL(clicked()),this,SLOT(slotCalled2()));
   // QObject::connect(qpb,SIGNAL(mysignal()),this,SLOT(slotCalled()));
    QObject::connect(this,SIGNAL(mysignal()),this,SLOT(slotCalled2()));
    QObject::connect(this,SIGNAL(mysignal()),this,SLOT(slotCalled3()));//one signal connected with 2 slots gets called in order of connect
}

//void MainWindow::mysignal()
//{
//    qDebug()<<"Signal is called.\n\n\n";
//}
void MainWindow::slotCalled()
{
    qDebug()<<"slotCalled"<<endl;
    //QString data = le->text();
   // qDebug()<<"data"<<data<<endl;
    //label1->setText(data);
    //label1->setText(le->text());
    qDebug()<<"emmitting mysignal from slotCalled()..."<<endl;
    emit mysignal();

}
void MainWindow::slotCalled2()
{
    qDebug()<<"slotCalled2"<<endl;
//    QString data = le->text();
//    qDebug()<<"data"<<data<<endl;
//    label1->setText(data);
    label1->setText(le->text());

}
void MainWindow::slotCalled3()
{
    qDebug()<<"slotCalled3"<<endl;
}

//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QLabel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    QLineEdit *le;
    Ui::MainWindow *ui;
    QPushButton *qpb ;
    QHBoxLayout *hl;
    QWidget *myWidget;
    QLabel *label1;
    QLabel *label2;
public slots:
    void slotCalled();
    void slotCalled2();
    void slotCalled3();
signals:
//    Q_SIGNALS:
    void mysignal();
public:
    void setUI();
};

#endif // MAINWINDOW_H
//mainwindow.ui
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow" >
  <property name="geometry" >
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle" >
   <string>MainWindow</string>
  </property>
  <widget class="QMenuBar" name="menuBar" />
  <widget class="QToolBar" name="mainToolBar" />
  <widget class="QWidget" name="centralWidget" />
  <widget class="QStatusBar" name="statusBar" />
 </widget>
 <layoutDefault spacing="6" margin="11" />
 <pixmapfunction></pixmapfunction>
 <resources/>
 <connections/>
</ui>
//Steps to build: download the source code in a folder. Navigate to the folder. qmake connectButtonClose.pro. then make.

Frequently asked questions in Qt interviews

What is DBus in Qt?

Q)What is D-Bus?
D-Bus is an IPC Mechanism in Linux.
D-Bus allows applications to expose internal API to the outside world by means of remotely callable interfaces.
These APIs can then be accessed at run-time via the D-Bus protocol using command line applications or D-Bus libraries and bindings themselves.
http://www.tune2wizard.com/linux-qt-signals-and-slots-qt-d-bus/
Defintion from others:
D-Bus  is  a  service  daemon  that  runs  in  the  background.  We  use  bus  daemons  to  interact  with  applications  and  their  functionalities.  The  bus  daemon forwards  and  receives  messages  to  and  from  applications.  There  are  two  types  of  bus  daemons:  SessionBus  and  SystemBus.
Before start doing any code, there is some terms that one should be familiar with:
http://linoxide.com/how-tos/d-bus-ipc-mechanism-linux/
http://www.linuxjournal.com/article/10455?page=0,1

Q) is This The Best Way?
Using QDBusMessage directly in this way to invoke remote D-Bus methods is not the easiest, best or even recommend way of doing things.
We will now look at the more convenient QDBusInterface class and then look at accessing remote D-Bus interfaces as if they were local methods using proxy classes auto-generated from XML.
https://techbase.kde.org/Development/Tutorials/D-Bus/Accessing_Interfaces
Note:
//Server/Application1 who will expose its function test() which can be invoked from other application2/client
#. Suppose a application(call server or daemon) willing to expose a function named "test()" in its mainwindow.h to other applications.
#. server app will generate a xml file with mainwindow.cpp containg the function to be exposed.
Command line was: qdbuscpp2xml mainwindow.h -o mainwindow.xml
#. server app will generate adapter .cpp and .h (when remote/client another app calls test of server function in adapter is also called.)
Command line was: qdbusxml2cpp -a test_adap mainwindow.xml
#. Server will create a session/sytem d-bus connection and register "service name" and "object name".(client app must mention these in proxy class object)
    new MainWindowAdaptor(&w);
    QDBusConnection connection = QDBusConnection::sessionBus();
    connection.registerService("manoj.test.service.name");
    connection.registerObject("/manojobjectpathname", &w);


    //test() can be called from client app by mentioning above service name and object name
    LocalMainWindowInterface *m_window = new LocalMainWindowInterface("manoj.test.service.name",
"/manojobjectpathname",
QDBusConnection::sessionBus(),
0);
    qDebug() << "Result from 1# " << m_window->test("via setParent");
#. Servie name: Service is program started by server/daemon to provide some functionality to other program. e.g. "manoj.test.service.name".
#. Object path name: "/manojobjectpathname"
#. Interface: are classes(p.v.f. or abstract class). that contain mehods and signals. Object name "/manojobjectpathname" has the interface "local.MainWindow" having interface class name as "LocalMainWindowInterface" which have method "Test()".

//Client or application2 who want to use function test() of server/daemon/application1
$. Suppose client/app2 wants to use the function test() exposed by the server/daemon/application1.
$. client application will generate proxy/interface files test_interface.cpp and test_interface.h using the mainwindow.xml of server application.
$. proxy files contains the proxy/remote class name "LocalMainWindowInterface" of server/daemon/app2 which contain the exposed function test().
$. From client app1, test() of server app2 can be called by creating object of proxy/remote class "LocalMainWindowInterface" already created in client app by mentioning the "service name" and "object path name".
   LocalMainWindowInterface *m_window = new LocalMainWindowInterface("manoj.test.service.name",
"/manojobjectpathname",
QDBusConnection::sessionBus(),
0);
m_window->test("via setParent");
Download the source code from 
https://github.com/manozsahu/dbusDemo1.git
https://github.com/manozsahu/dbusDemo2.git
You may also like

Qt moc FAQ Interview Questions

Q) What is Qt ?
Qt is a cross-platform application framework that is widely used for developing application software that can be run on various software and hardware platforms with little or no change in the underlying codebase,
Q) What is a framework?
framework  is an essential supporting structure of a building, vehicle, or object.
. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), which is overriden by user.
.Frameworks  is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality
Framework->uses your code.
Library->you use library code.
Q) What is qmake?
qmake is a utility that automates the generation of Makefiles.
Makefiles are used by the program make to build executable programs from source code; therefore qmake is a make-makefile tool, or makemake for short.
QMake does not call g++/gcc directly. Instead, qmake creates native make files on your current platform. Under linux it creates standard GNU make files, under windows it can generate visual studio make files, under Mac OS X it can generate XCode project files. You then invoke your native build system (either GNU make, or MS NMake, or xcodebuild or whatever), which will call your native compiler (g++/gcc or whatever).
Q) What is Qt and Qml ?
Qt is a cross-platform application framework.
QML is the name of the language (just like C++, which is another language...)
QML stands for Qt Meta Language or Qt Modelling Language is a user interface markup language.
QtQuick is a toolkit for QML, allowing to develop graphical interface in QML language (there are other toolkits for QML, some are graphical like Sailfish Silica or BlackBerry Cascade, and some are non-graphical like QBS which is a replacement for QMake/CMake/make...)
QtQuick 1.x was Qt4.x-based and used the QPainter/QGraphicsView API to draw the scene. QtQuick 2.X was introduced with Qt5.0, based on Scene Graph, an OpenGLES2 abstraction layer, highly optimized.
With Qt5.1, Scene Graph was enhanced to use multithreading (QtQuick 2.1) With Qt5.2,
Q)What is Qt's meta object system?
Qt's meta-object system provides the signals and slots mechanism for inter-object communication, run-time type information, and the dynamic property system.
The meta-object system is based on three things:
1. The QObject class provides a base class for objects that can take advantage of the meta-object system.
2. The Q_OBJECT macro inside the private section of the class declaration is used to enable meta-object features, such as dynamic properties, signals, and slots.
3. The Meta-Object Compiler (moc) supplies each QObject subclass with the necessary code to implement meta-object features.
The moc tool reads a C++ source file. If it finds one or more class declarations that contain the Q_OBJECTmacro, it produces another C++ source file which contains the meta-object code for each of those classes.
Q)What is moc? http://doc.qt.io/qt-4.8/moc.html
The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.
The moc tool reads a C++ header file.
1>If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes.and
2>meta-object code is required for the signals and slots mechanism and
3>moc is required for run-time type information, and the dynamic property system.
Note:
The C++ source file generated by moc must be compiled and linked with the implementation of the class.
But,If you use qmake to create your makefiles, build rules will be included that call the moc when required, so you will not need to use the moc directly.
Q) can moc file handle all class type?
No, class template can not have signal slot. can not be handled by moc.
Q) What are limitations of moc:
moc does not handle all of C++.e.g.
The main problem is that class templates cannot have signals or slots.
Function Pointers Cannot Be Signal or Slot Parameters
Type Macros Cannot Be Used for Signal and Slot Parameters
Nested Classes Cannot Have Signals or Slots
Signal/Slot return types cannot be references
Q) What is Qvariant?
QVariant is a container of variables. It can store variables of different types. Similar in some way to void*. But it provides You information about the stored type.
It can be used for example to return different types of values from a function.
Q)What is moc?
The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.
The moc tool reads a C++ header file.
1>If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes.and
2>meta-object code is required for the signals and slots mechanism and
3>moc is required for run-time type information, and the dynamic property system.
Note:
The C++ source file generated by moc must be compiled and linked with the implementation of the class.
But,If you use qmake to create your makefiles, build rules will be included that call the moc when required, so you will not need to use the moc directly.
 http://doc.qt.io/qt-4.8/moc.html

QThread FAQ in Interviews

Q) What is the entry point for qthread?
The run() implementation is for a thread what the main() entry point is for the application.
Q) Different types of thread?
http://blog.debao.me/2013/08/how-to-use-qthread-in-the-right-way-part-1/
http://ynonperek.com/course/qt/threads.html
First:
QThread MyThread;
this->moveToThread(&MyThread);
//”this” makes object of current class to run in thread
MyThread.start();
Second:
Subclass Qthread and override run()
Third:
QtConcurrent::run(this, &Camera::firstStartThreadProc);
OR
QFuture<void> f1 = QtConcurrent::run(this, &CanDTC::readThreadProc);
USAGE-01
#include <QtCore>
class Thread : public QThread
{
private:
    void run()
    {
        qDebug()<<"From worker thread: "<<currentThreadId();
    }
};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug()<<"From main thread: "<<QThread::currentThreadId();

    Thread t;
    QObject::connect(&t, SIGNAL(finished()), &a, SLOT(quit()));

    t.start();
    return a.exec();
}

Q) What happens if Qthread subclas declartion is in cpp and anot in header file?
You need to have a line at the bottom of your source file: #include "main.moc"
That's because the declaration of class Thread isn't in a header - it's in a .cpp file. So by default moc won't run on it. Adding the line does two things:
it signals to qmake and moc that moc has to process the .cpp file
it causes the stuff that moc generates to be pulled in by the compile step
So after adding that line you'll need to rerun qmake so it can update the makefiles to cause main.moc to be generated.

Q) What is the difference between QueuedConnection and normal connection in connect Qt?
// connect signal-slots for decoupling
QObject::connect (this, SIGNAL(setCurrentTaskSignal(int)), this,
    SLOT(SetCurrentTaskSlot(int)), Qt::QueuedConnection);
Note that QueuedConnection doesn't mean that something is in different thread. QueuedConnection means only that when signal is emitted, corresponding slot won't be called directly. It will be queued on event loop, and will be processed when control will be given back to event loop
One uses a queued connection to ensure that the signal will be delivered from within the event loop, and not immediately from the emit site as happens with direct connection. Direct connection is conceptually a set of calls to function pointers on a list. Queued connection is conceptually an event sent to a clever receiver who can execute a function call based on the contents of the event.

Qt.QueuedConnection -> When emitted, the signal is queued until the event loop is able to deliver it to the slot.

Qt.BlockingQueuedConnection -> Same as QueuedConnection, except that the current thread blocks until the slot has been delivered. This connection type should only be used for receivers in a different thread. Note that misuse of this type can lead to dead locks in your application.

Direct signal-slot connection is nothing else but a chain of synchronous or direct C++ function calls.
A queued signal-slot connection is nothing else but an asynchronous function call

Q) When is Qthread begin executing?
QThreads begin executing in run().
By default, run() starts the event loop by calling exec()...".

Q) By whom and when is run() method called in Qthread?
The run() method is called automagically by Qt when the caller calls start() on your thread

Q) How qthread can be used?
To be able to use one of the QThreadPool threads, we have to subclass QRunnable and implement the run() method. After that, we have to create an instance of the QRunnable subclass and pass it to QThreadPool::start().
//start->run->qthread.

Q)Wtat is the main difference between a process and a thread?
The main difference between a process and a thread is that each process is executed in a separate address space, whereas each thread uses the same address space of a process.
A process can have multiple threads.
Threads share the heap, but each thread of execution has its own call stack.

Q) Difference between QThread runnable and QtConcurrent?
QThread provides a low-level class that can be used for explicit creation of long-running threads.
Using QtConcurrent's functional map/filter/reduce algorithms, which apply functions in parallel to each item in a container, you can write a program that automatically takes advantage of the system's multiple cores by distributing the processing across the threads managed by the thread pool. Alternatively, you can use QRunnable as a base class for the Command pattern and schedule work with QtConcurrent::run(). In these cases, you do not need to create threads explicitly or manage them directly – you can simply describe the pieces of work as objects with the right interface.
QtConcurrent runs a pool of threads and it is a higher level API not well-suited to run a large number of blocking operations:
If you have CPU-bound work to do and want to distribute it across multiple cores, you can break up your work into QRunnables and make those thread-safe by following these recomendations.
Distribute the CPU-heavy calculations across multiple threads using QtConcurrent algorithms whenever possible, instead of writing your own QThread code.
Do not access the GUI (this includes any QWidget-derived class, QPixmap, and other graphics-card specific classes) from any thread other than the main thread. This includes read access like querying the text entered into a QlineEdit.

Q) Suppose your application needs to run a function in multiple threads the number of which is more than the number of CPU cores/threads.
 One way is to use QtConcurrent and setting the maximum thread count :
MyClass *obj = new MyClass;
QThreadPool::globalInstance()->setMaxThreadCount(30);
for(int i=0;i<30;i++)
    QtConcurrent::run(obj, &MyClass::someFunction);
Another way is to have multiple objects and move them to different threads using moveToThread :
for(int i=0;i<30;i++)
{
        MyClass *obj = new MyClass;
        QThread *th = new QThread();
        obj->moveToThread(th);
        connect(th, SIGNAL(started()), obj, SLOT(someFunction()) );
        connect(obj, SIGNAL(workFinished()), th, SLOT(quit()) );
        connect(th, SIGNAL(finished()), obj, SLOT(deleteLater()) );
        connect(th, SIGNAL(finished()), th, SLOT(deleteLater()) );
        th->start();
}

Frequently asked questions in Qt interviews

FAQ in Qt interviews:
Q) What is Qt?
Qt is a Framework that comprises of several classes that form the Qt object model. The root of this model is the QObject class. Basically all Qt objects inherit from the QObject class. Having inherited from this class, it means all Qt Objects inherit a particular behavior and we can exploit this in order to manage memory.
Q) How qt differs from other mobile development platforms like android?
i)Qt is platform independent- same source code can be used for development for multiple environment with no or very less code change. Android can be used in android environment only.
ii)Language independent- For development in Qt many languages like C++,C#,Java can be used. But in android Java is used.
Q) What are the striking features of QT?
Qt is cross platform application development framework using which application can be developed for different platform with no very less change in codebase.
Few features are:
Signal slots, moc, Qt D-bus,QtCore,QtWidget,QtGui,QML,QtMultimedia,Qt Network, Qt SQL, Qt xml.
Q) What is Qpointer?
QPointer:
It will be automatically set to nullptr if the pointed to object is destroyed. It is a weak pointer specialized for QObject.QPointer can only point to QObject instances.
You would normally use QPointer in a situation where the pointer is being created outside of a QObject class such as in the main function or other none Qt based classes you may have created in your code.
The QPointer is a template class that wraps obj as a pointer to MyObject. You will notice that there is no star to mark it as a pointer because QPointer abstracts all that. It does not just stop there but it also deals with dynamically destroying the obj pointer should there no longer be any references to it.

There you have it. A simple and safer way to use pointers and to manage your memory when programming in Qt C++.

Consider this fragment:

QObject *obj = new QObject;
QPointer<QObject> pObj(obj);
delete obj;
Q_ASSERT(pObj.isNull()); // pObj will be nullptr now

QSharedPointer
A reference-counted pointer. The actual object will only be deleted, when all shared pointers are destroyed. Equivalent to std::shared_ptr.

int *pI = new int;
QSharedPointer<int> pI1(pI);
QSharedPointer<int> pI2 = pI1;
pI1.clear();
// pI2 is still pointing to pI, so it is not deleted
pI2.clear();
// No shared pointers anymore, pI is deleted

Note that as long there is a shared pointer, the object is not deleted!

QWeakPointer:
Can hold a weak reference to a shared pointer. It will not prevent the object from being destroyed, and is simply reset. Equivalent to std::weak_ptr, where lock is equivalent to toStrongRef.

int *pI = new int;
QSharedPointer<int> pI1(pI);
QWeakPointer<int> pI2 = pI1;
pI1.clear();
// No shared pointers anymore, pI is deleted
//
// To use the shared pointer, we must "lock" it for use:
QSharedPointer<int> pI2_locked = pI2.toStrongRef();
Q_ASSERT(pI2_locked.isNull());

This can be used if you need access to an object that is controlled by another module.

To use a weak pointer, you must convert it to a QSharedPointer. You should never base a decision on the weak pointer being valid. You can only use data() of isNull to determine that the pointer is null.
Q) What is dpointer?
The d-pointer
The trick is to keep the size of all public classes of a library constant by only storing a single pointer. This pointer points to a private/internal data structure that contains all the data. The size of this internal structure can shrink or grow without having any side-effect on the application because the pointer is accessed only in the library code and from the application's point of view the size of the object never changes - it's always the size of the pointer. This pointer is called the d-pointer.
Q) What is MVC architecture? How it is organized?
MVC consists of three kinds of objects.
Model is the application object,
View is its screen presentation, and the
Controller defines the way the user interface reacts to user input.
Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse.
Model/view architecture to manage the relationship between data and the way it is presented to the user.
Q) What is a signal? And how will it differ from event?
Signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them.
signals: /* signals must be declared under 'signals:' or “ Q_SIGNALS:” access specifier */
void foo(); /* This is a signal declaration -- a pure declaration as a method.*/
Before Qt5 signals were protected so that only same class objects acan emit it.
From Qt5 onwards signals are public and to make it private need to declare QPrivateSignal dummy (empty) struct private in the Q_OBJECT macro.

In Qt, events are objects, derived from the abstract QEvent class, that represent things that have happened either within an application or as a result of outside activity that the application needs to know about. Events can be received and handled by any instance of a QObject subclass, but they are especially relevant to widgets. This document describes how events are delivered and handled in a typical application. in general an event will be generated by an outside entity (e.g. Keyboard, Mouswheel) and will be delivered through the event loop in QApplication.

Signals and Slots are a convenient way for QObjects to communicate with one another and are more similar to callback functions. In most circumstances, when a "signal" is emitted, any slot function connected to it is called directly. The exception is when signals and slots cross thread boundaries. In this case, the signal will essentially be converted into an event.

Q) What is a slot? And how it differs with callback Method?
Slots are normal C++ member functions and can be called normally; their only special feature is that signals can be connected to them. A slot is called when a signal connected to it is emitted. We can also define slots to be virtual.

Callbacks have two fundamental flaws: Firstly, they are not type-safe. We can never be certain that the processing function will call the callback with the correct arguments. Secondly, the callback is strongly coupled to the processing function since the processing function must know which callback to call.

Q) How many signals at maximum you can connect to a single slot? If more than one how you can do that?
Surely we can connect more than one signal to a single slot. The single slot is called whenever one of those connected signal is emmitted.
Even one signal can be coonected to another signal, which are then emitted automatically whenever the source signal is emitted. Definition for signals are genereated in by moc in code generated by moc.
Q) How many slots can you connect to a signal? If more than one how those slots will be executed?
(The order of execution).
Surely more than on slot can be connected to a single signal. Then Slots are called in the order they are connected when the signal is emmitted.
Q) What is QCast and how will it differ compared to c++’s dynamic cast?
qobject_cast function is used to convert polymorphic pointers on qobject classes.
qobject_cast does not reauire the support for rri while dynamic_cast requires to enable rtti.
Similar to dyanimc_cast it returns a non zero pointer on success ad 0 on failure.

For example,
let's assume MyWidget inherits from QWidget and is declared with the Q_OBJECT macro:
class MyWidget: public Qwidget
{
QObject *obj = new MyWidget;
...
};
The cast from QObject to QWidget must be successful, because the object obj is actually a MyWidget, which is a subclass of QWidget.

QWidget *widget = qobject_cast<QWidget *>(obj);

The cast from QObject to QWidget is successful, because the object is actually a MyWidget, which is a subclass of QWidget. Since we know that obj is a MyWidget, we can also cast it to MyWidget.

Q) What is the use of Q_OBJECT macro?
OBJECT simply tells the pre-compiler that this class has gui elements and needs to be run through the 'moc' . In turn moc generates definitions for member variables and functions that Q_OBJECT has declared. moc produces a C++ source file containing the meta-object code for those classes which declare Q_OBJECT and derived from QOBJECT or wants to use signal slot or wants to use qobject_cast.
The Q_OBJECT macro must appear in every class that derives from QObject or which wants to use signal slot mechanism, that want to use qobject_cast.

Q) What is MOC and UIC? Explain how they will work for compilation in QT?
The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.
The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information qobject_cast, and the dynamic property system.
Q) What is qmake? (Explain the usage of it)
Q) How a QT Program/Application written for one platform (Symbian) can be ported/executed in another
platform (Maemo)? (Explain If you need to make any changes or you need to recompile)
Q) What are all the platforms/OS currently QT supports?
Q) What is event loop in Qt?
18) How to design your own widget in Qt?
1).Signal/slot mechanism is synchronous or not? If it is,that means we should not let a slot do much work,otherwise the UI will be blocked for much time.?
Usually, slots are synchronous. Starting with Qt4, you can send signals across threads. If you execute a slot in another thread, you will get an asynchronous slot.
2).QEvent is asynchronous or not? For example ,if I call the update() function,the paintEvent() will be called, if it is asychronous,the UI will not be blocked.?
QEvents are syncronous but you can also deliver events in different slots. With Qt3, this was the only option to invoke something in a different thread.
3).Is there any relationship between signal/slot and event? Does Qt put the slots into event queue?
With Qt4, you can tell Qt to post signals in the event queue using the 5th argument of the connect-method.
1)Memory leak?
Memory leaks occur when pointers referencing a certain chunk of memory goes out of scope and therefore the pointer is lost but the content that the pointer was referencing is still lying in the heap. A pointer would normally go out of scope when an execution block ends and returns and the pointer created within that scope is not destroyed along with the referenced data. This can also occur when an exception is thrown or when any sort of error stops execution before the pointer is destroyed.
Qpointer is used in Qt framework to avoid such scenarios.

QPointer – This tracks the lifetime of an instance of QObject.
QSharedPointer, QWeakPointer – These are thread-safe sharing pointers, similar to C++11’s std::shared_ptr. QWeakPointer use has been deprecated unless used with QSharedPointer.
QScopedPointer, QScopedPointerArray – These are none shared pointers Ideal for Resource Acquisition Is Initialization (RAII) usage whereby they take ownership of a pointer and ensures it is properly deleted at the end of the scope.

Q ) What is D-Bus?
  • D-bus is inter process communication mechanism using which applications can communicate to each other.
  • Using dbus an application exposes its services with adapters.
  • Another application can use the services of other application using proxy by making it d-bus enabled.
Q) What is a System Bus?
  • Generally system bus starts with system's startup level.
  • Mainly used with hardwares events(like keyboard press or mouse click).
  • Event/interrupts/signals are signals from hw/sw to os/processor that it requirs quick attention from os/processor.
Q) What is a Session Bus?
  • Generally session bus starts when a user logins to desktop.
  • Mainly used for desktop applications to connect to each other.
Q) What is the syntax of a dbus?
Application one that exposes its services (say test()) creates xml using cpp2xml tool then creates adapter and proxy using xmltocpp tool and finally include adapter, registerService and registerObject.
new MainWindowAdaptor(&w);
QDBusConnection connection1 = QDBusConnection::sessionBus();
connection1.registerService("com.testServiceName");
connection1.registerObject("/testObjectPath",&w);
Another applicationTwo which wants to call services/methods exposed by the applicationOne include proxy, create proxy object and call the remote function on proxy object and in turn actual function in remote applicationOne gets called.
MyInterfaceClass * m_window = new MyInterfaceClass("com.testServiceName","/testObjectPath",QDBusConnection::sessionBus(),0);

Then call the function “test()” on remote application using local proxy objext as
m_window->test("via setParent");

Note:instead of 0 specific methods can be given.

Q) How to debug if a connect fails?
  • Check that classes using signals and slots inherit QObject or a QObject subclass.
  • Make sure the Q_OBJECT macro is inserted at the beginning of your class declaration.
  • If you use custom signals, check that these are declared correctly, with a void return type, in the public/protected/private signals section of your class declaration.
  • Make sure that your slot function is declared as a slot, e.g. private slots not private.
  • Put all connect statements before functions calls
  • Check the return value of the connect statement: connect returns true if it successfully connects the signal to the slot.
  • Use QErrorMessage::qtHandler() or qInstallMsgHandler() to view connect error warnings.
  • Put qDebug to check signal slots are called.
  • Check the compiler warnings.
Q) Can we give definition to user defined signal?
No, it will be a redefinition linker error because definition of signal is given in moc code.
Q) Can we connect a signal with another signal?
Yes, as both ara functions.
Example suppose a library code writeCode() emits a signal writeCompleted.
If another code say writeSocket uses the writeCode. On completion it emits another signal say writeSocketCompleted. So we can connect the signal writeSocketCompleted with writeCompleted.(without changing the library code)
Q) can slot have lesser arguments than signal? Yes
The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.)
This means that a signal of the form
signal(int, int, QString)
can only be connected with slots with the following signatures
slot1(int, int, QString)
slot2(int, int)
slot3(int)
slot4()
Q) can we overload function on basis of extern?
No, redefinition.
Q) Why multithreading is used?
1) efficient program to make best use of cpu cycles.
2) handling event driven code in ntworked, gui based, distributed code.
3) threads does not required ipc(like pipe,fifo,socket used in processes to communicate).
4)since threads run on the same address space of process so fast to create.
5) concurrent programming.

Q) How to use thread in Qt. Two ways?
1) creating a sub-class of QThread and implementing the run method then create object of this class and call start on that. Its old style like in java.
class SampleThread : public QThread
{
Q_OBJECT
protected:
virtual void run()
{
// do some work
qDebug() << "Hello from SampleThread: Thread Id:" << QThread::currentThreadId();
// Enters the main event loop and waits until exit() is called.
exec();
}
};
SampleThread aThread;
// start thread
aThread.start();
// check if thread running, returns true
qDebug()<< "thread running " << aThread.isRunning();
// check if thread finished, returns false
qDebug()<< "thread finished" << aThread.isFinished();
// terminate thread and wait for termination
aThread.quit();
aThread.wait();
// check if thread running, returns false
qDebug()<< "thread running " << aThread.isRunning();
// check if thread finished, returns true
qDebug()<< "thread finished" << aThread.isFinished();

Qii) can thread be connected to slots? Yes.
#include <QtCore>
class Thread : public QThread
{
private:
void run()
{
qDebug()<<"From worker thread: "<<currentThreadId();
}
};

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"From main thread: "<<QThread::currentThreadId();

Thread t;
QObject::connect(&t, SIGNAL(finished()), &a, SLOT(quit()));

t.start(); //start() calls the run() which is the entry point for a thread.
return a.exec();
}
/*output:
From main thread: 0x15a8
From worker thread: 0x128c
*/




2)Second way or new way of creating thread. more elegant way.
Subclass QThread and reimplement its run() function is intuitive and there are still many perfectly valid reasons to subclass QThread, but when event loop is used in worker thread, it's not easy to do it in the subclassing way.
Use worker objects by moving them to the thread is easy to use when event loop exists, as it has hidden the details of event loop and queued connection.

  1. Thread affinity was introduced at the base level of QObject, which is the base object for nearly all Qt related classes.
  2. Signal and slot connections can now be used between objects of different thread affinity.
3. QThread gained a default run implementation.

Example:
Usage 2-0

If we only want to make use of QThread::exec(), which has been called by QThread::run() by default, there will be no need to subclass the QThread any more.
Steps:
Create a Worker object
Do signal and slot connections
Move the Worker object to a sub-thread
Start thread

#include <QtCore>

class Worker : public QObject
{
Q_OBJECT
private slots:
void onTimeout()
{
qDebug()<<"Worker::onTimeout get called from?: "<<QThread::currentThreadId();
}
};

#include "main.moc"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"From main thread: "<<QThread::currentThreadId();

QThread t;
QTimer timer;
Worker worker;

QObject::connect(&timer, SIGNAL(timeout()), &worker, SLOT(onTimeout()));
timer.start(1000); //start() calls Qthread::run() which is the entry point for thread.

//timer.moveToThread(&t);
worker.moveToThread(&t);

t.start();

return a.exec();
}

/*
The result is:As expected, the slot doesn't run in the main thread.
From main thread: 0x1310
Worker::onTimeout get called from?: 0x121c
Worker::onTimeout get called from?: 0x121c
Worker::onTimeout get called from?: 0x121c
*/
Q) Command to count characters without opening it?
/prac$ wc -m < test.txt
29
test.txt contains: 29 characters including spaces and \0


Casting:
1) reinterpret_cast: used for i) casting between pointers of unrelated classes. ii) for ptr to int type cast.
2) const_cast: used to remove constantness.
3) dynamic_cast: is used to perform safe downcasting. Base ptr to derived class pointer.
4)static_cast: for implicit type conversions
i)non-const object to const,
ii) int to double.
iii) void* pointers to typed pointers,
iv)base pointers to derived pointers.
But it cannot cast from const to non-const object. This can only be done by const_cast operator.


1)
#include <iostream>
using namespace std;

struct data {
short a;
short b;
};

int main () {
long value = 0xA2345678;
data* pdata = reinterpret_cast<data*> (&value;);
cout << pdata->a << endl;
return 0;
}
Output on my machine: 22136 which is 2 bytes of value.

Another example might be:

class A {};
class B {};

int main()
{
A * pA = new A;
B * pB = reinterpret_cast<B*>(pA);
}
Qt example for displaying text from line edit to label on button click using signal and slots

What is DBus in Qt?