No, friend functions do not follow access specifier rules as they are not members function. Friend function declared in any access specfier can access private data of the class using object.
#include<iostream>
using namespace std;
class sample
{
private:
int a;
private:
void privateNormalFunction(){};
private:
friend void f1(sample);
protected:
void friend f2(sample);
public:
friend void f3(sample);
};
void f1(sample s)
{
s.a=10;
cout<<"f1::a"<<s.a<<endl;
}
void f2(sample s)
{
s.a=10;
cout<<"f2::a"<<s.a<<endl;
}
void f3(sample s)
{
s.a=10;
cout<<"f3::a"<<s.a<<endl;
}
int main()
{
sample s;
f1(s);
f2(s);
f3(s);
return 0;
}
Showing posts with label class. Show all posts
Showing posts with label class. Show all posts
Private virtual function
//Can virtual function be private?
//Suppose virtual function vf() is declared as private in base.Even though vf is overriden as public in derived compiler will throw error of private at run time. But one work around could be given to declare a virtual function as private by making main() as friend function of that class.Because friend functions can access the private members.
#include<iostream>
using namespace std;
class base
{
private:
virtual void vf(){cout<<"base::vf"<<endl;}
//friend int main();
};
class derived:public base
{
public:
void vf(){cout<<"derved::vf;"<<endl;}
};
int main()
{
base* bp = new derived;
bp->vf();//error: ‘virtual void base::vf()’ is private
return 0;
}
//Suppose virtual function vf() is declared as private in base.Even though vf is overriden as public in derived compiler will throw error of private at run time. But one work around could be given to declare a virtual function as private by making main() as friend function of that class.Because friend functions can access the private members.
#include<iostream>
using namespace std;
class base
{
private:
virtual void vf(){cout<<"base::vf"<<endl;}
//friend int main();
};
class derived:public base
{
public:
void vf(){cout<<"derved::vf;"<<endl;}
};
int main()
{
base* bp = new derived;
bp->vf();//error: ‘virtual void base::vf()’ is private
return 0;
}
Vtable, vptr content and size postmortem
#include<iostream>
using namespace std;
class EmptyClass
{};
class PolymorphicVF
{
virtual void vf(){}
};
class PolymorphicDesstructor
{
virtual ~PolymorphicDesstructor()
{
}
};
class PolymorphicPureDestructor
{
virtual ~PolymorphicPureDestructor()=0;
};
class AbstractClassWithOnePureVF
{
virtual void pvf()=0;
};
class classWithOnepureVFAnd4vf
{
virtual void vf1(){};
virtual void vf2(){};
virtual void pvf()=0;
virtual void vf3(){};
virtual void vf4(){};
};
class Base
{
public:
virtual void vf(){}
};
class SingleDerivedNoOverridevf: public Base
{
};
class SingleDerivedNoOverridevf1: public Base
{
};
class SingleDerivedNoOverridevf2AndOneDM: public Base
{
public:
char c;
};
class SingleDerivedWithOverridevf: virtual public Base
{
public:
void vf(){}
};
class SingleDerivedWithOverridevf1: virtual public Base
{
public:
void vf(){}
};;
class DiamiondProblemWithNoFinalOverrider:public SingleDerivedNoOverridevf, public SingleDerivedNoOverridevf1
{
};
class DiamiondProblemWithFinalOverrider:public SingleDerivedWithOverridevf, public SingleDerivedWithOverridevf1
{
void vf(){}
};
class DiamondDerivedWithThree:public SingleDerivedWithOverridevf, public SingleDerivedWithOverridevf1, public SingleDerivedNoOverridevf1
{
void vf(){}
};
class DerivedWithThreeDifferent:public EmptyClass,public PolymorphicVF,public PolymorphicDesstructor
{};
int main()
{
cout<<"sizeof(EmptyClass)="<<sizeof(EmptyClass)<<endl;//1
cout<<"sizeof(PolymorphicVF)="<<sizeof(PolymorphicVF)<<endl;//8
cout<<"sizeof(PolymorphicDesstructor)="<<sizeof(PolymorphicDesstructor)<<endl;//8
cout<<"sizeof(PolymorphicPureDestructor)="<<sizeof(PolymorphicPureDestructor)<<endl;//8
cout<<"sizeof(AbstractClassWithOnePureVF)="<<sizeof(AbstractClassWithOnePureVF)<<endl;//8
cout<<"sizeof(classWithOnepureVFAnd4vf)="<<sizeof(classWithOnepureVFAnd4vf)<<endl;//8
cout<<"sizeof(Base with one vf)="<<sizeof(Base)<<endl;//8
cout<<"sizeof(SingleDerivedNoOverridevf)="<<sizeof(SingleDerivedNoOverridevf)<<endl;//8
cout<<"sizeof(SingleDerivedNoOverridevf2AndOneDM)="<<sizeof(SingleDerivedNoOverridevf2AndOneDM)<<endl;//16
cout<<"sizeof(SingleDerivedWithOverridevf)="<<sizeof(SingleDerivedWithOverridevf)<<endl;//8
cout<<"sizeof(DiamiondProblemWithNoFinalOverrider)="<<sizeof(DiamiondProblemWithNoFinalOverrider)<<endl;//16
cout<<"sizeof(DiamiondProblemWithFinalOverrider)="<<sizeof(DiamiondProblemWithFinalOverrider)<<endl;//16
cout<<"sizeof(DiamondDerivedWithThree)="<<sizeof(DiamondDerivedWithThree)<<endl;//24
cout<<"sizeof(DerivedWithThreeDifferent)="<<sizeof(DerivedWithThreeDifferent)<<endl;//24
return 0;
}
/*
sizeof(EmptyClass)=1
sizeof(PolymorphicVF)=8
sizeof(PolymorphicDesstructor)=8
sizeof(PolymorphicPureDestructor)=8
sizeof(AbstractClassWithOnePureVF)=8
sizeof(classWithOnepureVFAnd4vf)=8
sizeof(Base with one vf)=8
sizeof(SingleDerivedNoOverridevf)=8
sizeof(SingleDerivedNoOverridevf2AndOneDM)=16
sizeof(SingleDerivedWithOverridevf)=8
sizeof(DiamiondProblemWithNoFinalOverrider)=16
sizeof(DiamiondProblemWithFinalOverrider)=16
sizeof(DiamondDerivedWithThree)=24
sizeof(DerivedWithThreeDifferent)=16
*/
//How to check content of vtable
//compiled with command:
//g++ -fdump-class-hierarchy vtable.cpp
//vtables are taken from generated class table file by above command:
//vtable.cpp.002t.class
Class EmptyClass
size=1 align=1
base size=0 base align=1
EmptyClass (0x0x7fc113139d80) 0 empty
//No vtable for non polymorphic class EmptyClass
Vtable for PolymorphicVF
PolymorphicVF::_ZTV13PolymorphicVF: 3u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI13PolymorphicVF)
16 (int (*)(...))PolymorphicVF::vf
Class PolymorphicVF
size=8 align=8
base size=8 base align=8
PolymorphicVF (0x0x7fc113139de0) 0 nearly-empty
vptr=((& PolymorphicVF::_ZTV13PolymorphicVF) + 16u)
using namespace std;
class EmptyClass
{};
class PolymorphicVF
{
virtual void vf(){}
};
class PolymorphicDesstructor
{
virtual ~PolymorphicDesstructor()
{
}
};
class PolymorphicPureDestructor
{
virtual ~PolymorphicPureDestructor()=0;
};
class AbstractClassWithOnePureVF
{
virtual void pvf()=0;
};
class classWithOnepureVFAnd4vf
{
virtual void vf1(){};
virtual void vf2(){};
virtual void pvf()=0;
virtual void vf3(){};
virtual void vf4(){};
};
class Base
{
public:
virtual void vf(){}
};
class SingleDerivedNoOverridevf: public Base
{
};
class SingleDerivedNoOverridevf1: public Base
{
};
class SingleDerivedNoOverridevf2AndOneDM: public Base
{
public:
char c;
};
class SingleDerivedWithOverridevf: virtual public Base
{
public:
void vf(){}
};
class SingleDerivedWithOverridevf1: virtual public Base
{
public:
void vf(){}
};;
class DiamiondProblemWithNoFinalOverrider:public SingleDerivedNoOverridevf, public SingleDerivedNoOverridevf1
{
};
class DiamiondProblemWithFinalOverrider:public SingleDerivedWithOverridevf, public SingleDerivedWithOverridevf1
{
void vf(){}
};
class DiamondDerivedWithThree:public SingleDerivedWithOverridevf, public SingleDerivedWithOverridevf1, public SingleDerivedNoOverridevf1
{
void vf(){}
};
class DerivedWithThreeDifferent:public EmptyClass,public PolymorphicVF,public PolymorphicDesstructor
{};
int main()
{
cout<<"sizeof(EmptyClass)="<<sizeof(EmptyClass)<<endl;//1
cout<<"sizeof(PolymorphicVF)="<<sizeof(PolymorphicVF)<<endl;//8
cout<<"sizeof(PolymorphicDesstructor)="<<sizeof(PolymorphicDesstructor)<<endl;//8
cout<<"sizeof(PolymorphicPureDestructor)="<<sizeof(PolymorphicPureDestructor)<<endl;//8
cout<<"sizeof(AbstractClassWithOnePureVF)="<<sizeof(AbstractClassWithOnePureVF)<<endl;//8
cout<<"sizeof(classWithOnepureVFAnd4vf)="<<sizeof(classWithOnepureVFAnd4vf)<<endl;//8
cout<<"sizeof(Base with one vf)="<<sizeof(Base)<<endl;//8
cout<<"sizeof(SingleDerivedNoOverridevf)="<<sizeof(SingleDerivedNoOverridevf)<<endl;//8
cout<<"sizeof(SingleDerivedNoOverridevf2AndOneDM)="<<sizeof(SingleDerivedNoOverridevf2AndOneDM)<<endl;//16
cout<<"sizeof(SingleDerivedWithOverridevf)="<<sizeof(SingleDerivedWithOverridevf)<<endl;//8
cout<<"sizeof(DiamiondProblemWithNoFinalOverrider)="<<sizeof(DiamiondProblemWithNoFinalOverrider)<<endl;//16
cout<<"sizeof(DiamiondProblemWithFinalOverrider)="<<sizeof(DiamiondProblemWithFinalOverrider)<<endl;//16
cout<<"sizeof(DiamondDerivedWithThree)="<<sizeof(DiamondDerivedWithThree)<<endl;//24
cout<<"sizeof(DerivedWithThreeDifferent)="<<sizeof(DerivedWithThreeDifferent)<<endl;//24
return 0;
}
/*
sizeof(EmptyClass)=1
sizeof(PolymorphicVF)=8
sizeof(PolymorphicDesstructor)=8
sizeof(PolymorphicPureDestructor)=8
sizeof(AbstractClassWithOnePureVF)=8
sizeof(classWithOnepureVFAnd4vf)=8
sizeof(Base with one vf)=8
sizeof(SingleDerivedNoOverridevf)=8
sizeof(SingleDerivedNoOverridevf2AndOneDM)=16
sizeof(SingleDerivedWithOverridevf)=8
sizeof(DiamiondProblemWithNoFinalOverrider)=16
sizeof(DiamiondProblemWithFinalOverrider)=16
sizeof(DiamondDerivedWithThree)=24
sizeof(DerivedWithThreeDifferent)=16
*/
//How to check content of vtable
//compiled with command:
//g++ -fdump-class-hierarchy vtable.cpp
//vtables are taken from generated class table file by above command:
//vtable.cpp.002t.class
Class EmptyClass
size=1 align=1
base size=0 base align=1
EmptyClass (0x0x7fc113139d80) 0 empty
//No vtable for non polymorphic class EmptyClass
Vtable for PolymorphicVF
PolymorphicVF::_ZTV13PolymorphicVF: 3u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI13PolymorphicVF)
16 (int (*)(...))PolymorphicVF::vf
Class PolymorphicVF
size=8 align=8
base size=8 base align=8
PolymorphicVF (0x0x7fc113139de0) 0 nearly-empty
vptr=((& PolymorphicVF::_ZTV13PolymorphicVF) + 16u)
Disadvantages of references in Cpp
References can not be re initialized. They always refer to first referent.
Reference arithmetic is not allowed. Operation effects on actual referent.
#include<iostream>
using namespace std;
int main()
{
int i=10;
int& j = i;
int & k =j;
cout<<"i: "<<i<<endl;
cout<<"j: "<<j<<endl;
cout<<"k: "<<k<<endl;
cout<<"&i: "<<&i<<endl;
cout<<"&j: "<<&j<<endl;
cout<<"&k: "<<&k<<endl;
//reference once initialized can not be reinitialed. point to first referent only.
int m=10;
int n=20;
int &x=m;
cout<<"x="<<x<<endl;//10
x=n;//this is not reassignment. actually its modifying value of m using x. this can be verified taking address of m and x as both would be same.
cout<<"x="<<x<<endl;//20
cout<<"m="<<m<<endl;//m gets modified to 20 now
cout<<"&x="<<&x<<endl;//0x7fff9671caf0
cout<<"&m="<<&m<<endl;//0x7fff9671caf0
//reference arithmatic is not allowed
int a=10;
int b=20;
int& ar=a;
cout<<"a="<<a<<endl;//10
cout<<"ar="<<ar<<endl;//10
ar++;//referant gets incremented not reference
cout<<"a="<<a<<endl;//11
cout<<"ar="<<ar<<endl;//11
return 0;
}
/*
i: 10
j: 10
k: 10
&i: 0x7fffee78603c
&j: 0x7fffee78603c
&k: 0x7fffee78603c
x=10
x=20
m=20
&x=0x7fffee786040
&m=0x7fffee786040
a=10
ar=10
a=11
ar=11
*/
Reference arithmetic is not allowed. Operation effects on actual referent.
#include<iostream>
using namespace std;
int main()
{
int i=10;
int& j = i;
int & k =j;
cout<<"i: "<<i<<endl;
cout<<"j: "<<j<<endl;
cout<<"k: "<<k<<endl;
cout<<"&i: "<<&i<<endl;
cout<<"&j: "<<&j<<endl;
cout<<"&k: "<<&k<<endl;
//reference once initialized can not be reinitialed. point to first referent only.
int m=10;
int n=20;
int &x=m;
cout<<"x="<<x<<endl;//10
x=n;//this is not reassignment. actually its modifying value of m using x. this can be verified taking address of m and x as both would be same.
cout<<"x="<<x<<endl;//20
cout<<"m="<<m<<endl;//m gets modified to 20 now
cout<<"&x="<<&x<<endl;//0x7fff9671caf0
cout<<"&m="<<&m<<endl;//0x7fff9671caf0
//reference arithmatic is not allowed
int a=10;
int b=20;
int& ar=a;
cout<<"a="<<a<<endl;//10
cout<<"ar="<<ar<<endl;//10
ar++;//referant gets incremented not reference
cout<<"a="<<a<<endl;//11
cout<<"ar="<<ar<<endl;//11
return 0;
}
/*
i: 10
j: 10
k: 10
&i: 0x7fffee78603c
&j: 0x7fffee78603c
&k: 0x7fffee78603c
x=10
x=20
m=20
&x=0x7fffee786040
&m=0x7fffee786040
a=10
ar=10
a=11
ar=11
*/
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;
}
#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;
}
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
*/
#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
#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
*/
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;
}
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:
#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:
C++ reference FAQ interview questions
//1.References are nothing but constant pointer.
//2.So,references once initialized can not refer to other.
//2.1 Reference to reference not allowed.No error but. it will start pointing to the first variable
//3. reference arithmatic not allowed.No error in reference arithmatic but changes reflected in referant not in reference.
//4.Reference to array allowed.//int (&r)[5];
//5.Array of reference not allowed because we can not find the address of array. ultimately refer to first variable.
//6.Unlike pointers,refernce are automatically gets dereferenced.No need to use *(value at address).
//7.Unlike pointers, reference arithmatic like increment will increase the referant's value and not the address
//8.Reference are used to pass by reference to get the changes reflected in calling function.
//9.Pass by reference avoids copy of large value when structure like data are passed as arguments.
//10. Its unsafe to return local variable by value because variable goes out of scope once conrol returns out of the function defintion.
//Solution is us local static variable or dynamic memory allocation so that scope of the variable will through out the program.
#include<iostream>
using namespace std;
int gv;
int main()
{
//reference nothing but constant pointer means once initialized can not be reinitialized.
int s=10;
int *const h=&s;//s is const pointer so can not hold another address
//h=&m;//error: assignment of read-only variable ‘h’
int i=10,m=2;
int &j=i;// j is reference to a
//reference to refernce not allowed. No error but points to the first variable
int &k=j;//reference to reference no error but//point 2.1
k=20;
cout<<i<<endl;//20
//pointer arithmatic are not allowed. no error but changes gets reflected in first variable
k++;//point 7
cout<<i<<endl;//21
//referece can not be reinitialized but direct values can be given
int a=1;
k=1;
cout<<k<<endl;
//pass by reference to get the values reflected in calling function
int x=10,y=20;
swap(x,y);
cout<<x<<" " <<y<<endl;//20,10
//if return type is reference then function call can be made in left side
int &f();
f()=5;
cout<<"gv="<<gv<<endl;//5//instead of returned reference 100, f() is assigned to 5
//problem of local ovariable returning by value
int d;
int ff(d);
cout<<"d="<<d<<endl;//Garbage, because return value went out of scope in definition itself.
return 0;
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=x;
}
//return by reference
int &f()
{
gv=100;
return gv;
}
//problem of returning local variable by value
int ff(int t)
{
int& lv=t;
lv=lv+44;
return lv;//returning local variable by value.
}//scope of lv over here
You may also like.
//2.So,references once initialized can not refer to other.
//2.1 Reference to reference not allowed.No error but. it will start pointing to the first variable
//3. reference arithmatic not allowed.No error in reference arithmatic but changes reflected in referant not in reference.
//4.Reference to array allowed.//int (&r)[5];
//5.Array of reference not allowed because we can not find the address of array. ultimately refer to first variable.
//6.Unlike pointers,refernce are automatically gets dereferenced.No need to use *(value at address).
//7.Unlike pointers, reference arithmatic like increment will increase the referant's value and not the address
//8.Reference are used to pass by reference to get the changes reflected in calling function.
//9.Pass by reference avoids copy of large value when structure like data are passed as arguments.
//10. Its unsafe to return local variable by value because variable goes out of scope once conrol returns out of the function defintion.
//Solution is us local static variable or dynamic memory allocation so that scope of the variable will through out the program.
#include<iostream>
using namespace std;
int gv;
int main()
{
//reference nothing but constant pointer means once initialized can not be reinitialized.
int s=10;
int *const h=&s;//s is const pointer so can not hold another address
//h=&m;//error: assignment of read-only variable ‘h’
int i=10,m=2;
int &j=i;// j is reference to a
//reference to refernce not allowed. No error but points to the first variable
int &k=j;//reference to reference no error but//point 2.1
k=20;
cout<<i<<endl;//20
//pointer arithmatic are not allowed. no error but changes gets reflected in first variable
k++;//point 7
cout<<i<<endl;//21
//referece can not be reinitialized but direct values can be given
int a=1;
k=1;
cout<<k<<endl;
//pass by reference to get the values reflected in calling function
int x=10,y=20;
swap(x,y);
cout<<x<<" " <<y<<endl;//20,10
//if return type is reference then function call can be made in left side
int &f();
f()=5;
cout<<"gv="<<gv<<endl;//5//instead of returned reference 100, f() is assigned to 5
//problem of local ovariable returning by value
int d;
int ff(d);
cout<<"d="<<d<<endl;//Garbage, because return value went out of scope in definition itself.
return 0;
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=x;
}
//return by reference
int &f()
{
gv=100;
return gv;
}
//problem of returning local variable by value
int ff(int t)
{
int& lv=t;
lv=lv+44;
return lv;//returning local variable by value.
}//scope of lv over here
You may also like.
Find and remove loop in linked list code in cpp linux
//Remove Loop in a linked list1.
//Find the loop and pass the loop node to removeLoop function.
//assign pointer ptr1=start.
//start infinite loop.
//assign pointer ptr2=loopnode.
//in loop traverse till ptr2->next!=loopnode && ptr2->next!=ptr1
//loop is found when ptr2->next=ptr1 ; break the loop
//else increment ptr1//most important
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
//Inserting at start
void insert(struct node** ref,int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=(*ref);
*ref=newnode;//mind it
}
//displaying
void display(struct node *ref)
{
struct node *ptr=ref;
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
//Detecting Loop
void loopDetect()
{
struct node* slow=start;
struct node* fast=start;
while(start->next !=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
printf("LoopDetected\n");
removeLoop(slow);
break;//else infinite time LoopDetected gets printed
}
}
}
void removeLoop(struct node *loopnode)
{
printf("\nRemoveLoop Called.\n");
struct node *ptr1;
struct node *ptr2;
ptr1=start;
while(1)
{
ptr2=loopnode;
while(ptr2->next != loopnode && ptr2->next!=ptr1)
{
ptr2=ptr2->next;
}
if(ptr2->next==ptr1)//mind the next
break;
else
ptr1=ptr1->next;
}
ptr2->next=NULL;
}
int main()
{
insert(&start,10);
insert(&start,20);
insert(&start,30);
insert(&start,40);
insert(&start,50);
display(start);
//create a loop
start->next->next->next->next=start->next;
//display(start);//infinite loop means loop created.
loopDetect();
display(start);//No infinite loop means No loop now.
return 0;
}
/*
50 40 30 20 10
LoopDetected
50 40 30 20
*/
--------------------------
//Remove Loop in a linked list1.
//Find the loop and pass the loop node to removeLoop function.
//assign pointer ptr1=start.
//start infinite loop.
//assign pointer ptr2=loopnode.
//in loop traverse till ptr2->next!=loopnode && ptr2->next!=ptr1
//loop is found when ptr2->next=ptr1 ; break the loop
//else increment ptr1//most important
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
//Inserting at start
void insert(struct node** ref,int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=(*ref);
*ref=newnode;//mind it
}
//displaying
void display(struct node *ref)
{
struct node *ptr=ref;
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
//Detecting Loop
void loopDetect()
{
struct node* slow=start;
struct node* fast=start;
while(start->next !=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
printf("LoopDetected\n");
removeLoop(slow);
break;//else infinite time LoopDetected gets printed
}
}
}
void removeLoop(struct node *loopnode)
{
printf("\nRemoveLoop Called.\n");
struct node *ptr1;
struct node *ptr2;
ptr1=start;
while(1)
{
ptr2=loopnode;
while(ptr2->next != loopnode && ptr2->next!=ptr1)
{
ptr2=ptr2->next;
}
if(ptr2->next==ptr1)//mind the next
break;
else
ptr1=ptr1->next;
}
ptr2->next=NULL;
}
int main()
{
insert(&start,10);
insert(&start,20);
insert(&start,30);
insert(&start,40);
insert(&start,50);
display(start);
//create a loop
start->next->next->next->next=start->next;
//display(start);//infinite loop means loop created.
loopDetect();
display(start);//No infinite loop means No loop now.
return 0;
}
/*
50 40 30 20 10
LoopDetected
50 40 30 20
*/
--------------------------
//Remove Loop in a linked list1.
Singleton Design Pattern example in C++
//Singleton is a creational design pattern.
//A design pattern to provide one and only instance of an object.
//Declare the constructors of the class private.
//Declatre a static public instance of class type.
//Provide a static public method to get the instance
//If instance is NULL then only once create a object else
//return the already created instance
#include<stdio.h>
using namespace std;
class singleton
{
private:
singleton(){printf("Constructor called only once.\n");}
public:
static singleton* instance;
static singleton* getinstance();
};
singleton* singleton::instance=NULL;
singleton* singleton::getinstance()
{
if(instance==NULL)
{
instance = new singleton;//mind the syntax//no singleston s;
}
else
{
return instance;
}
}
int main()
{
//singleton s1;//singleton() is private within this context
singleton *sptr;
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
return 0;
}
/*
Constructor called only once.
*/
//A design pattern to provide one and only instance of an object.
//Declare the constructors of the class private.
//Declatre a static public instance of class type.
//Provide a static public method to get the instance
//If instance is NULL then only once create a object else
//return the already created instance
#include<stdio.h>
using namespace std;
class singleton
{
private:
singleton(){printf("Constructor called only once.\n");}
public:
static singleton* instance;
static singleton* getinstance();
};
singleton* singleton::instance=NULL;
singleton* singleton::getinstance()
{
if(instance==NULL)
{
instance = new singleton;//mind the syntax//no singleston s;
}
else
{
return instance;
}
}
int main()
{
//singleton s1;//singleton() is private within this context
singleton *sptr;
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
return 0;
}
/*
Constructor called only once.
*/
Observer Design Pattern example in C++
Observer Design Pattern example in C++
//Observer Design pattern Best Example.
//Observer Design pattern is implemented using two classes.
//First is observable or subject class: in this class even occurs and to be notified to the registered observers.
//subject class contains attachObserver(), notifyObserver(),and other task.
//Second class is observer class: class which wants to be notified when some even occurs in observable or subject class.
//observer class contains a pure viryual function notify().
//Example:
//When any event like new blog/article is available in a website it should notify to all the registered users.
//So here Blog will derived from subject class and
//users want to get notified of new articles. So User will be derived from class observer
#include<iostream>
using namespace std;
#include <vector>
#include <typeinfo>
#include <string>
class Subject;//forward declaration
class Observer//class which are interested to get notified
{
public:
virtual void notify(Subject* s) = 0;//pure virtual function
virtual ~Observer() {};
};
class Subject//Class in which even take place
{
vector<Observer *> observers;
protected:
void notify_observers()
{
vector<Observer *>::iterator iter;
for (iter = observers.begin(); iter != observers.end(); ++iter)
(*iter)->notify(this);
}
public:
virtual ~Subject() {};
void register_observer(Observer* o)//pusshing the attached observers in a vector
{
observers.push_back(o);
}
};
class Blog : public Subject
{
public:
Blog()
{
cout << "New Article Posted." << "\n";
}
void eventTriggerNewArticle()
{
cout << "The new article event is triggered." << "\n";
notify_observers();
}
int const get_Blog_id()
//int get_Blog_id()
{
return 21022015;
}
};
class User : public Observer
{
public:
virtual void notify(Subject* s)
{
Blog *a;
a = dynamic_cast<Blog*>(s);
cout << a->get_Blog_id() << "\n";
}
};
int main ()
{
Blog newArticle = Blog();
User u = User();
newArticle.register_observer(&u);
newArticle.eventTriggerNewArticle();
return 0;
}
/*OUTPUT:
New Article Posted.
The new article event is triggered.
21022015
*/
//Observer Design pattern is implemented using two classes.
//First is observable or subject class: in this class even occurs and to be notified to the registered observers.
//subject class contains attachObserver(), notifyObserver(),and other task.
//Second class is observer class: class which wants to be notified when some even occurs in observable or subject class.
//observer class contains a pure viryual function notify().
//Example:
//When any event like new blog/article is available in a website it should notify to all the registered users.
//So here Blog will derived from subject class and
//users want to get notified of new articles. So User will be derived from class observer
#include<iostream>
using namespace std;
#include <vector>
#include <typeinfo>
#include <string>
class Subject;//forward declaration
class Observer//class which are interested to get notified
{
public:
virtual void notify(Subject* s) = 0;//pure virtual function
virtual ~Observer() {};
};
class Subject//Class in which even take place
{
vector<Observer *> observers;
protected:
void notify_observers()
{
vector<Observer *>::iterator iter;
for (iter = observers.begin(); iter != observers.end(); ++iter)
(*iter)->notify(this);
}
public:
virtual ~Subject() {};
void register_observer(Observer* o)//pusshing the attached observers in a vector
{
observers.push_back(o);
}
};
class Blog : public Subject
{
public:
Blog()
{
cout << "New Article Posted." << "\n";
}
void eventTriggerNewArticle()
{
cout << "The new article event is triggered." << "\n";
notify_observers();
}
int const get_Blog_id()
//int get_Blog_id()
{
return 21022015;
}
};
class User : public Observer
{
public:
virtual void notify(Subject* s)
{
Blog *a;
a = dynamic_cast<Blog*>(s);
cout << a->get_Blog_id() << "\n";
}
};
int main ()
{
Blog newArticle = Blog();
User u = User();
newArticle.register_observer(&u);
newArticle.eventTriggerNewArticle();
return 0;
}
/*OUTPUT:
New Article Posted.
The new article event is triggered.
21022015
*/
C++ program to overload operator+ for string concatenation
//operator overloading for concatenating two strings in C++
#include<iostream>
using namespace std;
#include<string.h>
class sample
{
private:
char str[20];
public:
sample()
{
cout<<"def constructor."<<endl;
strcpy(str,"C++ Linux Code.");
}
sample(char s[])
{
cout<<"a arg constructor."<<endl;
strcpy(str,s);
}
sample operator+(const sample& ref )
{
cout<<"overloaded + called"<<endl;
sample temp;//def constructor
strcpy(temp.str,str);
strcat(temp.str,ref.str);
return temp;
}
//return *this;//seg fault
void display(){cout<<str<<endl;}
};
int main()
{
sample s1;//def constructor
s1.display();
sample s2("blogspot.com");//1 arg constructor
s2.display();
sample s3;//def constructor
s3=s1+s2;
s3.display();
//cout<<str<<endl;//str was not declared in this scope. As str is private and only mf can access
//cout<<s1.str<<endl;//aaa
//cout<<'m'<<endl;//a
return 0;
}
/*
def constructor.
C++ Linux Code.
a arg constructor.
blogspot.com
def constructor.
overloaded + called
def constructor.
C++ Linux Code.blogs
*/
#include<iostream>
using namespace std;
#include<string.h>
class sample
{
private:
char str[20];
public:
sample()
{
cout<<"def constructor."<<endl;
strcpy(str,"C++ Linux Code.");
}
sample(char s[])
{
cout<<"a arg constructor."<<endl;
strcpy(str,s);
}
sample operator+(const sample& ref )
{
cout<<"overloaded + called"<<endl;
sample temp;//def constructor
strcpy(temp.str,str);
strcat(temp.str,ref.str);
return temp;
}
//return *this;//seg fault
void display(){cout<<str<<endl;}
};
int main()
{
sample s1;//def constructor
s1.display();
sample s2("blogspot.com");//1 arg constructor
s2.display();
sample s3;//def constructor
s3=s1+s2;
s3.display();
//cout<<str<<endl;//str was not declared in this scope. As str is private and only mf can access
//cout<<s1.str<<endl;//aaa
//cout<<'m'<<endl;//a
return 0;
}
/*
def constructor.
C++ Linux Code.
a arg constructor.
blogspot.com
def constructor.
overloaded + called
def constructor.
C++ Linux Code.blogs
*/
Observer Design Pattern example in C++
Singleton Design Pattern example in C++
C++ program to overload operator+ for string concatenation
Copy constructor Overloaded assignment operator Destructor and default constructor implementation in C++
C++ program to implement:Default constructor, One argument constructor, Copy constructor, overloaded assignment operator, destructor and overload + operator to concatenate two strings in a single program.
#include<iostream>
using namespace std;
#include<string.h>
class sample
{
private:
char *name;
public:
sample(){cout<<"\n Default constructor called."<<endl;}
sample(const char *p);
sample(const sample &ref);
sample& operator=(const sample &obj);
sample& operator+(const sample& obj);
~sample();
};
sample::sample(const char* p)
{
cout<<" One argument constructor called."<<endl;
name = new char[strlen(p)+1];
strcpy(name,p);
cout<<"name: "<<name<<endl;
}
sample::sample(const sample &ref)
{
cout<<"copy constructor called."<<endl;
name=new char[strlen(ref.name)+1];
strcpy(name,ref.name);
}
sample& sample::operator=(const sample &ref)
{
cout<<"overloaded = operator called.\n";
//if(this==&ref)
//return *this;
//delete[] name;//Seg fault
name=new char[strlen(ref.name)+1];
strcpy(this->name,ref.name);
return *this;
}
sample& sample::operator+(const sample &obj)
{
cout<<"overloaded + called.\n";
//name=new char[strlen(obj.name)+1];
strcat(name,obj.name);
cout<<"cancatename is: "<<name<<endl;
}
sample::~sample()
{
cout<<"Destructor called.\n";
//delete[] name;
}
int main()
{
sample s1;//def constr.//destr
sample s2("Hello");//1 arg constr.//destr
sample s3(s2);//copy constr.//destr
sample s4=s3;//copy constr.//destr
sample s5;//def constr.//destr
s5=s1;//overloaded = opr.//No destructor
s2+s3;//overloaded + called//No destr
//cout<<s2.name<<endl;//name is private and accessible only by mf
return 0;
}
/*OUTPUT:
Default constructor called.
One argument constructor called.
name: Hello
copy constructor called.
copy constructor called.
Default constructor called.
overloaded = operator called.
overloaded + called.
cancatename is: HelloHello
Destructor called.
Destructor called.
Destructor called.
Destructor called.
Destructor called.
*/
#include<iostream>
using namespace std;
#include<string.h>
class sample
{
private:
char *name;
public:
sample(){cout<<"\n Default constructor called."<<endl;}
sample(const char *p);
sample(const sample &ref);
sample& operator=(const sample &obj);
sample& operator+(const sample& obj);
~sample();
};
sample::sample(const char* p)
{
cout<<" One argument constructor called."<<endl;
name = new char[strlen(p)+1];
strcpy(name,p);
cout<<"name: "<<name<<endl;
}
sample::sample(const sample &ref)
{
cout<<"copy constructor called."<<endl;
name=new char[strlen(ref.name)+1];
strcpy(name,ref.name);
}
sample& sample::operator=(const sample &ref)
{
cout<<"overloaded = operator called.\n";
//if(this==&ref)
//return *this;
//delete[] name;//Seg fault
name=new char[strlen(ref.name)+1];
strcpy(this->name,ref.name);
return *this;
}
sample& sample::operator+(const sample &obj)
{
cout<<"overloaded + called.\n";
//name=new char[strlen(obj.name)+1];
strcat(name,obj.name);
cout<<"cancatename is: "<<name<<endl;
}
sample::~sample()
{
cout<<"Destructor called.\n";
//delete[] name;
}
int main()
{
sample s1;//def constr.//destr
sample s2("Hello");//1 arg constr.//destr
sample s3(s2);//copy constr.//destr
sample s4=s3;//copy constr.//destr
sample s5;//def constr.//destr
s5=s1;//overloaded = opr.//No destructor
s2+s3;//overloaded + called//No destr
//cout<<s2.name<<endl;//name is private and accessible only by mf
return 0;
}
/*OUTPUT:
Default constructor called.
One argument constructor called.
name: Hello
copy constructor called.
copy constructor called.
Default constructor called.
overloaded = operator called.
overloaded + called.
cancatename is: HelloHello
Destructor called.
Destructor called.
Destructor called.
Destructor called.
Destructor called.
*/
Observer Design Pattern example in C++
Singleton Design Pattern example in C++
C++ program to overload operator+ for string concatenation
Subscribe to:
Posts (Atom)