Linked list opeartions at middle

//nexted list to insert middle
#include <iostream>
using namespace std;
#include<stdio.h>
struct node
{
int data;
node* next;
};
struct node* first=NULL;
struct node* prev=NULL;
struct node* ptr=NULL;
struct node* last=NULL;
void insert_middle();
void display();
void deleteKey();
int main()
{
display();
deleteKey();
display();
insert_middle();
display();
insert_middle();
display();
insert_middle();
display();
//insert_middle();
//display();
deleteKey();
display();
deleteKey();
display();
deleteKey();
display();
deleteKey();
display();
return 0;
}
void insert_middle()
{
cout<<"insert_middle"<<endl;
node *newnode = new node;
cout<<"Enter the data to insert:"<<endl;
cin>>newnode->data;
newnode->next=NULL;
int pos;
cout<<"Enter the position to enter:"<<endl;
cin>>pos;
int length=0;
node* ptr=first;
while(ptr)
{
ptr=ptr->next;
length++;
}
//cout<<"length="<<length<<endl;
if(pos==1)//111111111
{
    if(first==NULL)
    {
    first=last=newnode;
    first->next=NULL;
    last->next=NULL;
    }
    else
    {
    newnode->next=first;
    first=newnode;
    }
}
else if(pos >1 && pos <=length)////////////2-length
{
    ptr=first;
    for(int i =1; i<pos;i++)
    {
    prev=ptr;
    ptr=ptr->next;
    }
    prev->next=newnode;
    newnode->next=ptr;
}
else//out side of length
{
cout<<"Out of range....Inserting at last"<<endl;
    if(first==NULL)
    {
    first=last=newnode;
    first->next=NULL;
    last->next=NULL;
     }
     else
     {
     ptr=first;
      while(ptr->next!=NULL)//ptr-next is must as segflt
      {
      ptr=ptr->next;
      }
       ptr->next=newnode;
       newnode->next=NULL;
     }
 }
}
void display()
{
cout<<"display"<<endl;
node* current=first;
while(current!=NULL)
{
cout<<current->data<<" ";
current=current->next;
}
cout<<endl;
}
void deleteKey()
{
cout<<"delteKey"<<endl;
int key;
    if(first == NULL)
    {
        printf("\nEmpty Linked List. Deletion not possible.\n");
    }
    else
    {
        printf("\nEnter the data of the node to be deleted: ");
        scanf("%d", &key);
        ptr = first;
        while((ptr->next != NULL) && (ptr->data != key))
        {
            cout<<"while"<<endl;
            prev = ptr;
            ptr = ptr->next;
        }
        if(ptr->data == key)
        {
            if(ptr==first)
            {
            cout<<"if"<<endl;
            node * temp=first;
            first=first->next;
            delete temp;   
            }
            else
            {
            cout<<"else"<<endl;
            prev->next = ptr->next;
            delete ptr;   
            }
            printf("\nNode with data %d deleted.\n", key);
        }
        else
        {
            printf("\nValue %d not found. Deletion not possible.\n", key);
        }       
    }
}
/*output
display
delteKey
Empty Linked List. Deletion not possible.
display
insert_middle
Enter the data to insert:
11
Enter the position to enter:
1
display
11
insert_middle
Enter the data to insert:
22
Enter the position to enter:
1
display
22 11
insert_middle
Enter the data to insert:
33
Enter the position to enter:
2
display
22 33 11
delteKey
Enter the data of the node to be deleted: 11
while
while
else
Node with data 11 deleted.
display
22 33
delteKey
Enter the data of the node to be deleted: 22
if
Node with data 22 deleted.
display
33
delteKey
Enter the data of the node to be deleted: 22
Value 22 not found. Deletion not possible.
display
33
delteKey
Enter the data of the node to be deleted: 33
if
Node with data 33 deleted.
display
*/

Casting examples in C++ Linux


#include <QCoreApplication>
#include <iostream>
using namespace std;
class A
{
};
class B
{
};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<"Hello"<<endl;

    A *aa = new A;

//    B *bb = static_cast<B*>(aa);//Invalid cast A* to B*
//    B *bb = const_cast<B*>(aa);//Invalid cast A* to B*
//    B *bb = dynamic_cast<B*>(aa);//Invalid cast A* to B* source is not polymorphic
      B *bb = reinterpret_cast<B*>(aa);//OK
    return a.exec();
}
//---------------------------
#include <QCoreApplication>
#include <iostream>
using namespace std;
class A
{
public:
    virtual ~A(){}//making source A as polymorphic
};
class B
{

};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<"Hello"<<endl;

    A *aa = new A;

//    B *bb = static_cast<B*>(aa);//Invalid cast A* to B*
//    B *bb = const_cast<B*>(aa);//Invalid cast A* to B*
      B *bb1 = dynamic_cast<B*>(aa);//Compiles ok but run time crash
      B *bb2 = reinterpret_cast<B*>(aa);//OK
    return a.exec();
}
//-----------------------------------------
#include <QCoreApplication>
#include <iostream>
using namespace std;
class A
{
};
class B:public A
{
};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<"Hello"<<endl;
    A *aa = new A;
    B *bb1 = static_cast<B*>(aa);//Ok
    //B *bb2 = const_cast<B*>(aa);//Invalid cast A* to B*
    //B *bb3 = dynamic_cast<B*>(aa);//Invalid cast A* to B*
    B *bb4 = reinterpret_cast<B*>(aa);//OK
    return a.exec();
}

//-----------------------------------------
#include <QCoreApplication>
#include <iostream>
using namespace std;
class A
{
public:
    virtual ~A(){}
};
class B:public A
{
};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<"Hello"<<endl;
    A *aa = new A;
    B *bb1 = static_cast<B*>(aa);//Ok
    //B *bb2 = const_cast<B*>(aa);//Invalid cast A* to B*
    B *bb3 = dynamic_cast<B*>(aa);//ok
    B *bb4 = reinterpret_cast<B*>(aa);//OK
    return a.exec();
}
//Dynamic Cast demos
Dynamic_cast is used for down casting  polymorphic base pointer to derived class poinetr to access member function defined by derived class in safe way.
#include <iostream>
#include <exception>
using namespace std;
class base { virtual void dummy() {} };
class derived: public base { int a; };
int main ()
 {
      try
            {
                base * pba = new derived;
                base * pbb = new base;
                derived * pd;
                pd = dynamic_cast<derived*>(pba);//d to b dynamic_cast ok
                              //because polymorphic base class elese run time error
                if (pd == 0)
                    cout << "Null pointer on first type-cast" << endl;
                pd = dynamic_cast<derived*>(pbb);
                if (pd == 0)
                    cout << "Null pointer on second type-cast" << endl;//gets printed
            }
            catch (exception& e)
            {
                cout << "Exception: " << e.what();
            }
            return 0;
        }
      
      #include <iostream>
        #include <typeinfo>
        using namespace std;
        int main ()
        {
            int * a;
            int b;
            a = 0; b = 0;
            if (typeid(a) != typeid(b))
            {
                cout << typeid(a).name()<<endl;//pi
                cout << typeid(b).name()<<endl;//i
            }
            return 0;
        }
Example Code:
        #include <iostream>
        #include <typeinfo>
        #include <exception>
        using namespace std;
        class base
        {
            virtual void f(){}
        };
        class derived : public base {};
        int main ()
        {
            try
            {
                base* a = new base;
                base* b = new derived;
                cout << typeid(*a).name() << '\n';//4base
                cout << typeid(*b).name()<<"\n";//7derived
            }
            catch (exception& e)
            {
                cout << "Exception: " << e.what() << endl;
            }
            return 0;
        }
Example Code:
        #include <typeinfo>
        #include <iostream>
        using namespace std;
        class A
        {
            public:
            virtual ~A();
        };
        int main()
        {
            A* a = NULL;
            try
            {
                cout << typeid(*a).name() << endl;
            }
            catch (bad_typeid)
            {
                cout << "Object is NULL" << endl;
            }
        }
Example Code:
        #include <iostream>
        using namespace std;
        struct A
        {
            virtual void f() 
            {
                cout << "Class A" << endl;
            }
        };
        struct B : A
        {
            virtual void f()
            {
                cout << "Class B" << endl;
            }
        };
        struct C : A
        {
            virtual void f()
            {
                cout << "Class C" << endl;
            }
        };
        void f(A* arg)
        {
            B* bp = dynamic_cast<B*>(arg);
            C* cp = dynamic_cast<C*>(arg);
            if (bp)
                bp -> f();
            else if (cp)
                cp -> f();
            else
                arg -> f(); 
        };
        int main()
        {
            A aobj;
            C cobj;
            A* ap = &cobj;
            A* ap2 = &aobj;
            f(ap);
            f(ap2);
        }
/*
class C
Class A
*/
Example Code:
#include<iostream>
using namespace std;
class Base
{
public:
virtual    void f(){cout<<"Base::f"<<endl;}
};
class Derive:public Base
{
public:
virtual     void f(){cout<<"Derived::f"<<endl;}
};
int main()
{
//CASE 1----------------------------------------------------------------
//Base *b = new Derive();
Base *pb;
Derive *pd;
//pb=pd;//No error
//pd=pb;error: invalid conversion from ‘Base*’ to ‘Derive*’

pb = dynamic_cast<Base*>(pd);
if(pd!=NULL)
{
cout<<"derive to base pass\n";
//pd->f();//run time crash
//pb->f();// run time rash
}
else if(pd==NULL)
{
cout<<"derive to base fail\n";
}
Base *b = new Derive();
Base *pb2;
Derive *pd2;
//pb2=pd2;//No error
//pd2=pb2;//error: invalid conversion from ‘Base*’ to ‘Derive*’

//CASE 2------------------------------------------------------------------
b = dynamic_cast<Base*>(pd2);
if(pd2!=NULL)
{
cout<<"derive to base pass2\n";
//pd2->f();//run time crash
//pb2->f();// run time rash
}
else if(pd2==NULL)
{
cout<<"derive to base fail2\n";
}
//CASE 3---------------------------------------------------------------
//Base *b = new Derive();
cout<<"31"<<endl;
Base *pb3;
cout<<"32"<<endl;
Derive *pd3;
cout<<"33"<<endl;
//pb=pd;//No error
//pd=pb;error: invalid conversion from ‘Base*’ to ‘Derive*’
/*
pd3 = dynamic_cast<Derive*>(pb3);//BOOOOM
cout<<"34"<<endl;
if(pb3!=NULL)
{
cout<<"base to derive pass 3\n";
}
else if(pb3==NULL)
{
cout<<"base to derive 3\n";
}
*/
//CASE 4-------------------------------------------------------------------
Base *b4 = new Derive();
//Base *pb4;
Derive *pd4;
pd4 = dynamic_cast<Derive*>(b4);//BOOM
cout<<"44"<<endl;
//if(pb4!=NULL)
//{
//cout<<"pb4 base to derive pass4\n";
//}
//else if(pb4==NULL)
//{
//cout<<"pb4 base to derive fail4\n";
//}

if(b4!=NULL)
{
cout<<"b4 base to derive pass4\n";
b4->f();//Derive::f
}
else if(b4==NULL)
{
cout<<"b4 base to derive fail4\n";
}
if(pd4!=NULL)
{
cout<<"pd4 base to derive pass4\n";
pd4->f();//Derive::f()
}
else if(pd4==NULL)
{
cout<<"pd4 base to derive fail4\n";
}
return 0;
}
Example Code:
#include<iostream>
using namespace std;
class Base
{
public:
    virtual void f(){cout<<"Base::f"<<endl;}
};
class Derive:public Base
{
public:
    virtual void f(){cout<<"iDerived::f"<<endl;}
};
int main()
{
Base *b = new Derived;
return 0;
}

        #include <iostream>
        using namespace std;
        struct A
        {
            virtual void f() 
            {
                cout << "Class A" << endl;
            }
        };
        struct B : A
        {
            virtual void f()
            {
                cout << "Class B" << endl;
            }
        };
        struct C : A
        {
            virtual void f()
            {
                cout << "Class C" << endl;
            }
        };
        void f(A* arg)//cobj the aobj
        {
            B* bp = dynamic_cast<B*>(arg);//cobj to bobj fails //arg2. aobj to bobj fails
            C* cp = dynamic_cast<C*>(arg);//cobj to cobj pass //arg2.  aobj to cobj fails

            if (bp)
        {
        cout<<"bp\n";
                bp -> f();
        }
            else if (cp)
        {
        cout<<"cp\n";
                cp -> f();
        }
            else
        {
        cout<<"else\n";
                arg -> f(); 
        }
        };
        int main()
        {
            A aobj;
            C cobj;
            A* ap = &cobj;
            f(ap); //Cp C

            A* ap2 = &aobj;
            f(ap2);//else A

        }
 

Number programs in C C++ asked in interviews

//C/CPP/C++ linux code to find factorial of a given number
#include <iostream>
using namespace std;
int main()
{
int n,i=1,f=1;
cout<<"Enter a number whose factorial is required:"<<endl;
cin>>n;//5
while(i<=n)
{
f=f*i;
i++;
}
cout<<"factorial is:"<<f<<endl;
return 0;
}
//C/CPP/C++ linux code to find fibonacci series
#include <iostream>
using namespace std;
int main()
{
int n,first=0,second=1,next;
cout<<"Enter upto which fibonacci needed:"<<endl;
cin>>n;
cout<<first<<"\t"<<second<<"\t";
for(int i=0;i<n;i++)
{
next=first+second;
first=second;
second=next;
cout<<next<<"\t";
}
cout<<endl;
return 0;
}
//C/CPP/C++ linux code to check given number is palindrom or not
////C/CPP/C++ linux code to find sum of digits of given number
#include <iostream>
using namespace std;
int main()
{
int n,r,s=0;
cout<<"Enter a number whose digits needs to be added:"<<endl;
cin>>n;//123
int temp=n;
while(n)
{
r=n%10;
n=n/10;
s=s*10+r;
}
cout<<"revers of "<<temp<<" is: "<<s<<endl;//6
if(s==temp)
cout<<"Yes "<<temp<<" and "<<s<<" are palindrome"<<endl;
else
cout<<"No "<<temp<<" and "<<s<<" are not palindrome"<<endl;
return 0;
}
//C/CPP/C++ linux code to check given number is prime or not
#include<iostream>
using namespace std;
int main()
{
int n,i,count=0;
cout<<"Enter a number to check its prime or not?"<<endl;
cin>>n;
cout<<n<<endl;
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
count++;
break;
}
}
if(count>0)
cout<<"Not prime"<<endl;
else
cout<<"prime"<<endl;

return 0;
}
//C/CPP/C++ linux code to find prime numbers in range
//prime in series
#include<iostream>
using namespace std;
int main()
{
int n,i,count,min,max;
cout<<"Enter a min number of range to check prime:"<<endl;
cin>>min;
cout<<"Enter the max number of range to check prime:"<<endl;
cin>>max;
for(n=min;n<=max;n++)
{
count=0;
    for(i=2;i<=n/2;i++)
    {
        if(n%i==0)
        {
        count++;
        break;
    }
}
if(count==0 && n!=1 && n!=0)
cout<<n<<endl;
//else
//cout<<"Not a prime"<<endl;
}
return 0;
}
//C/CPP/C++ linux code to reverse digits of a number
#include <iostream>
using namespace std;
int main()
{
int n,r,s=0;
cout<<"Enter a number:"<<endl;
cin>>n;//123
int temp=n;
while(n)
{
r=n%10;
n=n/10;
s=s*10+r;
}
cout<<"revers n "<<temp<<"is:"<<s<<endl;//6
return 0;
}
//C/CPP/C++ linux code to add digits of number
#include <iostream>
using namespace std;
int main()
{
int n,r,s=0;
cout<<"Enter a number whose needs to be added:"<<endl;
cin>>n;//123
while(n)
{
r=n%10;
n=n/10;
s=s+r;
}
cout<<"Sum of digits of n "<<n<<"is:"<<s<<endl;//6
return 0;
}
//C/CPP/C++ linux code to find a year is leap year or not
#include<stdio.h>
int main()
{
int year;
  printf("Enter a year to check if it is a leap year\n");
  scanf("%d", &year);
  if ( year%400 == 0)
    printf("%d is a leap year.\n", year);
  else if ( year%100 == 0)
    printf("%d is not a leap year.\n", year);
  else if ( year%4 == 0 )
    printf("%d is a leap year.\n", year);
  else
    printf("%d is not a leap year.\n", year);
return 0;
}
//C/CPP/C++ linux code to revert bit at given position
#include <iostream>
using namespace std;
void bitSet(int,int);
void showBit(int);
int main()
{
int n,b;
cout<<"Enter a number and bit postion you want to revert:"<<endl;
cin>>n>>b;
bitSet(n,b);
return 0;
}
void showBit(int n)
{
cout<<"n="<<n<<endl;
unsigned int s=1;
s=s<<sizeof(int)*8-1;
while(s>0)
{
if(n&s)
cout<<"1";
else
cout<<"0";
s=s>>1;
}
cout<<endl;
}
void bitSet(int n, int b)
{
cout<<"n="<<n<<" b="<<b<<endl;
showBit(n);
unsigned int s=1;
s=s<<b-1;
n=n|s;
cout<<"after Setting bit"<<endl;
showBit(n);
}
/*
6
4
n=6 b=4
n=6
00000000000000000000000000000110
after Setting bit
n=14
00000000000000000000000000001110

*/
//C/CPP/C++ linux code to find endianness of your PC
#include<stdio.h>
int main()
{
   unsigned int i = 1;
   char *c = (char*)&i;/*a character pointer c is pointing to an integer i*/
   if (*c)    /*Since size of character is 1 byte when the character pointer is de-referenced it will contain only first byte of integer.*/
    printf("Your machine is Little endian.\n");//01 00 00 00 because 01 means 1 and true//My Machine
  
else
       printf("It is a Big endian Machine.\n");//00 00 00 01
  
   return 0;
}

Template Method and template class example in C++ Linux

How to use template in C++:
Template is mechanism in C++ to generate family of
 generic classes and generic functions that works with
different types of data types hence eliminate duplicate
 program for different data types and make the program
 more manageable and easier.
C++ Program for 1 argument template class
#include<iostream.h>
#include<string.h>
template <class T>
class test
{
T t;
public:
test(T x)//will work with int, float,char,string
{
t=x;
}
 void show(void)
 {
  cout<<"t= "<<t<<endl;
 }
};
//void test< T>::show(void)
//{
//cout<<"t"<<t<<endl;
//}
int main()
{
test<int>t1(10); //calls int version of test(T t)
t1.show();
test<float>t2(1.0);  //calls float version of test(T t)
t2.show();
test<char>t3('m');   //calls char version of test(T t)
t3.show();
test<char *>t4("HelloTemplate"); // calls string version of test(T t)
t4.show();
return 0;
}
C++ Program for 1 argument template function

#include<iostream.h>
//using namespace std
template <class T>
void display(T a)
{
cout<<a<<endl;
}
int main()
{
display(10);
display(20.12);
display('M');
display("MamaMeaa");
return 0;

}
 
//Template method example
#include<iostream>
using namespace std;
template<typename T1, typename T2>
void add(T1 a, T2 b)
{
    cout<<"\nSum : "<<a+b<<endl;
}

template<typename T3, typename T4>
T3 addSameAndReturn(T3 a, T4 b)//T1 T1
{
return a+b;
}
int main ()
{
    add(4,5.5454);//9.5454
    //specify types while passing values to funcion
    add<int,double>(4,5.5454);//9.5454
    add<float,int>(4.7,5); //9.7
    add<string,string>("hi","bye");//hibye

cout<<"addSameAndReturn(10.2,10.3)="<<addSameAndReturn(10.2,10.3)<<endl;//20.5
cout<<"addSameAndReturn(10,10.3)="<<addSameAndReturn<int,float>(10,10.3)<<endl;//20
cout<<"addSameAndReturn(10,10.3)="<<addSameAndReturn<float,int>(10.3,10)<<endl;//20.3

    return 0;
}

Pthread example code in C++ with and without synchronization

//Thread example in C++. One thread should prints odd numbers and the other thread should print the even numbers. Example without synchronization.
#include<iostream>
using namespace std;
int count=0; //global variable accessed by two threads
int maxx=10;
void* even(void *v)
{
cout<<"even thread"<<endl;
while(count<maxx)
{
if((count%2)==0)
{
cout<<count++<<" ";
//count++;
}
}
pthread_exit(0);//pthread_exit is called from the thread itself to terminate its execution (and return a result) early.
}
void* odd(void *o)
{
cout<<"odd thread"<<endl;
while(count<maxx)
{
if((count%2)==1)
{
cout<<count++<<" ";
//count++;// then proper order :)
}
}
pthread_exit(0);
}

int main()
{
pthread_t t1;
pthread_t t2;

pthread_create(&t1,NULL,&even,NULL);
pthread_create(&t2,NULL,&odd,NULL);
pthread_join(t1,0);
pthread_join(t2,0);
//pthread_join is called from another thread to wait for a thread to terminate and obtain its return value
cout<<endl;
return 0;
}
//OUTPUT
~$ g++ test1.cpp -lpthread
~$ ./a.out
even thread
0 odd thread
1 3 2 5 4 76  89 
//Improved Example synchronized using mutex and conditional variable.
#include<iostream>
using namespace std;
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.
        }
        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
        }
        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;
}
/*
odd 0
even1
odd 2
even3
odd 4
even5
odd 6
even7
odd 9
even10
*/

Simple logger class implementation code example in c++

//main.cpp
#include "Logger.h"
int main(int argc, char *argv[])
{
    string message1 = "logg message 1 ...";
    string message2 = "logg message 2 ...";
    int    nNum     = 10;
    CLogger::getLogger()->Log("\nmessage to be logged------------------>\n");
    CLogger::getLogger()->Log(message1);
   
    CLogger::getLogger()->Log("\nmessage to be loggedi again-------------------->\n");
    LOGGER->Log("\nMessage is:%s Number is:%d",message1.c_str(), nNum,"\n");//#define LOGGER CLogger::getLogger()

    CLogger::getLogger()->Log("\nmessage to be loggedi again------------------------>\n");
    CLogger *ptr1;
    ptr1=CLogger::getLogger();
    ptr1->Log("\nMessage Logged\n");           

}
//logger.h
#ifndef CUSTOM_CLogger_H
#define CUSTOM_CLogger_H
#include <fstream>
#include <iostream>
#include <cstdarg>
#include <string>
using namespace std;
#define LOGGER CLogger::getLogger()
/**
 *   Singleton Logger Class.
 */
class CLogger
{
public:
    /**
     *   Logs a message
     *   @param sMessage message to be logged.
     */
    void Log(const std::string& sMessage);
    /**
     *   Variable Length Logger function
     *   @param format string for the message to be logged.
     */
    void Log( const char * format, ... );
        /**
     *   << overloaded function to Logs a message
     *   @param sMessage message to be logged.
     */
    CLogger& operator<<(const string& sMessage );
    /**
     *   Funtion to create the instance of logger class.
     *   @return singleton object of Clogger class..
     */
    static CLogger* getLogger();
private:
    /**
     *    Default constructor for the Logger class.
     */
    CLogger();
    /**
     *   copy constructor for the Logger class.
     */
    CLogger( const CLogger&){};             // copy constructor is private
    /**
     *   assignment operator for the Logger class.
     */
    CLogger& operator=(const CLogger& ){ return *this;};  // assignment operator is private
    /**
     *   Log file name.
     **/
    static const std::string m_sFileName;
    /**
     *   Singleton logger class object pointer.
     **/
    static CLogger* m_pThis;
    /**
     *   Log file stream object.
     **/
    static ofstream m_Logfile;
};
#endif
//logger.cpp
#include "Logger.h"
//#include"Utilities.h"
const string CLogger::m_sFileName = "Log.txt";
CLogger* CLogger:: m_pThis = NULL;
ofstream CLogger::m_Logfile;
CLogger::CLogger()
{

}
CLogger* CLogger::getLogger(){
    if(m_pThis == NULL){
        m_pThis = new CLogger();
        m_Logfile.open(m_sFileName.c_str(), ios::out | ios::app );
    }
    return m_pThis;
}

void CLogger::Log( const char * format, ... )
{
    char sMessage[256];
    va_list args;
    va_start (args, format);
    vsprintf (sMessage,format, args);
//    m_Logfile <<"\n"<<Util::CurrentDateTime()<<":\t";
    m_Logfile << sMessage;
    va_end (args);
}

void CLogger::Log( const string& sMessage )
{
    //m_Logfile <<"\n"<<Util::CurrentDateTime()<<":\t";
    m_Logfile << sMessage;
}

CLogger& CLogger::operator<<(const string& sMessage )
{
    //m_Logfile <<"\n"<<Util::CurrentDateTime()<<":\t";
    m_Logfile << sMessage;
    return *this;
}
//Log.txt

message to be logged------------------>
logg message 1 ...
message to be loggedi again-------------------->

Message is:logg message 1 ... Number is:10
message to be loggedi again------------------------>

Message Logged
//Courtesy cppcodetips.wordpress.com

Initialization List examples code in C++ in Linux

/*1) For initialization of non-static const data members:
const data members must be initialized using Initializer List. In the following example, “t” is a const data member of Test class and is initialized using Initializer List.
*/
#include<iostream>
using namespace std;

class Test {
    const int t;
public:
    Test(int t):t(t){} //error: assignment of read-only member ‘Test::t’ if assignment is used
    //Test(int t){this->t=t;} //error: assignment of read-only member ‘Test::t’ if assignment is used
    int getT() { return t; }
};

int main() {
    Test t1(10);
    cout<<t1.getT()<<endl;;
    return 0;
}

/* OUTPUT:
   10
*/
/*2) For initialization of reference members:
Reference members must be initialized using Initializer List. In the following example, “t” is a reference member of Test class and is initialized using Initializer List.
// Initialization of reference data members*/
#include<iostream>
using namespace std;

class Test {
    int& t;
public:
    Test(int &t):t(t) {cout<<"constructor\n";}
    //Test(int &t) {this->t=t;}  //error: uninitialized reference member ‘Test::t’
    int getT() { return t; }
};

int main() {
    int x = 20;
    Test t1(x);
    cout<<t1.getT()<<endl;
    x = 30;
    cout<<t1.getT()<<endl;
int y=100;
    cout<<t1.getT()<<endl;

//    Test t(400);//error: no matching function for call to ‘Test::Test(int)’
    return 0;
}
/* OUTPUT:
    20
    30
    30
 */
//3.//Initialer list is used for initializing contained class object which does not have a default copy constructor.
#include <iostream>
using namespace std;

class A {
    int i;
public:
    A(int );
};

A::A(int arg) {
    i = arg;
    cout << "A's Constructor called: Value of i: " << i << endl;
}

// Class B contains object of A
class B {
    A a;
public:
    B(int );
};

B::B(int x):a(x) {  //Initializer list must be used
    cout << "B's Constructor called";
}

int main() {
    B obj(10);
    return 0;
}
/* OUTPUT:
    A's Constructor called: Value of i: 10
    B's Constructor called
*/
/*4) For initialization of base class members : Like point 3, parameterized constructor of base class can only be called using Initializer List.*/
#include <iostream>
using namespace std;

class A {
    int i;
public:
    A(int );
};

A::A(int arg) {
    i = arg;
    cout << "A's Constructor called: Value of i: " << i << endl;
}

// Class B is derived from A
class B: A {
public:
    B(int );
};

B::B(int x):A(x) { //Initializer list must be used
    cout << "B's Constructor called"<<endl;
}

int main() {
    B obj(10);
    return 0;
}
/*
A's Constructor called: Value of i: 10
B's Constructor called
*/
/*5) When constructor’s parameter name is same as data member
If constructor’s parameter name is same as data member name then the data member must be initialized either using this pointer or Initializer List. In the following example, both member name and parameter name for A() is “i”.
*/
#include <iostream>
using namespace std;

class A {
    int i;
public:
    A(int );
    int getI() const { return i; }
};

//A::A(int i):i(i) { }  // Either Initializer list or this pointer must be used
// The above constructor can also be written as
A::A(int i) {
    this->i = i;
    //i = i;//some garbage
}


int main() {
    A a(10);
    cout<<a.getI()<<endl;
    return 0;
}
/* OUTPUT:
    10
*/

Factory Design pattern code example in C++

Factory Design pattern is achieved in 2 ways:
1. By giving a abstract interface class or and giving object create method in concrete class derived from interface class
2. By giving object create method in Factory class
2.  Factory Design pattern: defines interface to create objects. Object creation not required directly by client instead it is created in provided interface. Advantage is that client does not require to know exact class name whose object it wants to create. Also object instantiation is delayed till factory's create() method call so its like virtual constructor as exact class name is not required during compile time.
#include<iostream>
using namespace std;
#include<string.h>
class Button
{
public:
    virtual void paintButton()=0;
};
class OsLinuxButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsLinuxButton::paintButton"<<endl;
    }   
};
class OsWindowButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsWindowButton::paintButton"<<endl;
    }   
};
class GuiFactory
{
public:
    virtual Button* createButton(char* but)//No abstract
    {
    if(strcmp(but,"window")==0)
    {
    return new OsWindowButton;
    }
    if(strcmp(but,"linux")==0)
    {
    return new OsLinuxButton;
    }
    }
};
class Factory: public GuiFactory
{
public:
    Button* createButton(char* but)
    {
    if(strcmp(but,"window")==0)
    {
    return new OsWindowButton;
    }
    if(strcmp(but,"linux")==0)
    {
    return new OsLinuxButton;
    }
    }
};

int main()
{
Button *button1;
GuiFactory * guifactory=new Factory;
button1 = guifactory->createButton("window");
button1->paintButton();

Button *button2;
GuiFactory * guifactory2=new Factory;
button2 = guifactory->createButton("linux");
button2->paintButton();
return 0;
}

Example 2:
//Abstract factory Design pattern: defines interface to create family of objects. Object creation not required directly by client instead it is created in provided interface. Advantage is that client does not require to know exact class name whose object it wants to create. Also objectinstantiation is delayed till factory's create() method call so its like virtual constructor as exact class name is not required during compile time.
#include<iostream>
using namespace std;
#include<string.h>
class Button
{
public:
    virtual void paintButton()=0;
};
class OsLinuxButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsLinuxButton::paintButton"<<endl;
    }  
};
class OsWindowButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsWindowButton::paintButton"<<endl;
    }  
};
/*
class GuiFactory
{
public:
    virtual Button* createButton(char* but)=0;
};
class Factory: public GuiFactory
{
public:
    Button* createButton(char* but)
    {
    if(strcmp(but,"window")==0)
    {
    return new OsWindowButton;
    }
    if(strcmp(but,"linux")==0)
    {
    return new OsLinuxButton;
    }
    }
};
*/
int main()
{
/*
Button *button1;
GuiFactory * guifactory=new Factory;
button1 = guifactory->createButton("window");
button1->paintButton();

Button *button2;
GuiFactory * guifactory2=new Factory;
button2 = guifactory->createButton("linux");
button2->paintButton();
*/
//Without factory Object is ctreated in client code itself.
//client does new so may effect the code. Separate interface is not defined to create object.
Button *button=new OsLinuxButton;
button->paintButton();

Button *buttonWindow=new OsWindowButton;
buttonWindow->paintButton();
return 0;
}

Abstract factory Design pattern code example in cpp

Abstract factory Design pattern: defines interface to create family of objects. Object creation not required directly by client instead it is created in provided interface. Advantage is that client does not require to know exact class name whose object it wants to create. Also object instantiation is delayed till factory's create() method call so its like virtual constructor as exact class name is not required during compile time.
#include<iostream>
using namespace std;
#include<string.h>
class Button
{
public:
    virtual void paintButton()=0;
};
class OsLinuxButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsLinuxButton::paintButton"<<endl;
    }   
};
class OsWindowButton: public Button
{
public:
    void paintButton()
    {
    cout<<"OsWindowButton::paintButton"<<endl;
    }   
};
class GuiFactory
{
public:
    virtual Button* createButton(char* but)=0;
};
class Factory: public GuiFactory
{
public:
    Button* createButton(char* but)
    {
    if(strcmp(but,"window")==0)
    {
    return new OsWindowButton;
    }
    if(strcmp(but,"linux")==0)
    {
    return new OsLinuxButton;
    }
    }
};

int main()
{
Button *button1;
GuiFactory * guifactory=new Factory;
button1 = guifactory->createButton("window");
button1->paintButton();

Button *button2;
GuiFactory * guifactory2=new Factory;
button2 = guifactory->createButton("linux");
button2->paintButton();
return 0;
}

Example2: