Skip to main content

25 posts tagged with "C++"

View All Tags

'Factory Method' Design Pattern using simple program

· One min read

Definition:

Creates an instance of several derived classes. or Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Program:

#include "iostream"
using namespace std;

class Product
{
public:
virtual void Show() = 0;
};

class ConcreteProductA : public Product
{
public:
virtual void Show()
{
cout<<"ConcreteProductA"<<endl;
}
};

class ConcreteProductB : public Product
{
public:
virtual void Show()
{
cout<<"ConcreteProductB"<<endl;
}
};

class Creator
{
public:
virtual Product* FactoryMethod() = 0;
};

class ConcreteCreatorA : public Creator
{
public:
ConcreteCreatorA() {}
virtual Product* FactoryMethod()
{
return new ConcreteProductA();
}
};

class ConcreteCreatorB : public Creator
{
public:
virtual Product* FactoryMethod()
{
return new ConcreteProductB();
}
};

void main()
{
Creator* creators[2];

creators[0] = new ConcreteCreatorA();
creators[1] = new ConcreteCreatorB();

for (int i=0; i < 2; i++) { Product* product = creators[i]->FactoryMethod();
cout<<"Created "<<Show();
}

getchar();
}

/*
OUT PUT
-------
Created
ConcreteProductA
Created
ConcreteProductB
*/

'Singleton' Design Pattern using simple program

· One min read

Definition: Ensure a class only has one instance and provide a global point of access to it.

Program:

#include "iostream"
using namespace std;

class Singleton
{
private:
static Singleton* instance;
Singleton() {}

public:
static Singleton* Instance()
{
if(instance == NULL)
{
instance = new Singleton();
}
return instance;
}

void Show()
{
cout&lt;&lt;"Singleton Class"&lt;&lt;endl;
}
};

Singleton* Singleton::instance = NULL;

int main()
{
Singleton* obj1 = Singleton::Instance();
obj1->Show();

Singleton* obj2 = Singleton::Instance();
obj2->Show();

getchar();

return 0;
}

/*
OUT PUT
-------
Singleton Class
Singleton Class
*/

‘AbstractFactory’ Design Pattern using simple program

· 2 min read

Definition: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Program:


#include "iostream"
using namespace std;

// Abstract Factory pattern
class AbstractProductA
{
public:
virtual void Show() = 0;
};

class AbstractProductB
{
public:
virtual void Show() = 0;
};

class AbstractFactory
{
public:
virtual AbstractProductA* CreateProductA() = 0;
virtual AbstractProductB* CreateProductB() = 0;
};

class ProductA1 : public AbstractProductA
{
public:
virtual void Show()
{
cout<<"ProductA1 Show"<<endl;>
}
};

class ProductB1 : public AbstractProductB
{
public:
virtual void Show()
{
cout<<"ProductB1 Show"<<endl;>
}
};

class ProductA2 : public AbstractProductA
{
public:
virtual void Show()
{
cout<<"ProductA2 Show"<<endl;
}
};

class ProductB2 : public AbstractProductB
{
public:
virtual void Show()
{
cout<<"ProductB2 Show"<<endl;
}
};

class ConcreteFactory1 : public AbstractFactory
{
public:
virtual AbstractProductA* CreateProductA()
{
return new ProductA1();
}

virtual AbstractProductB* CreateProductB()
{
return new ProductB1();
}
};

class ConcreteFactory2 : public AbstractFactory
{
public:
virtual AbstractProductA* CreateProductA()
{
return new ProductA2();
}

virtual AbstractProductB* CreateProductB()
{
return new ProductB2();
}
};

class Client
{
private:
AbstractProductA* _abstractProductA;
AbstractProductB* _abstractProductB;

public:
Client(AbstractFactory\* factory)
{
_abstractProductB = factory->CreateProductB();
_abstractProductA = factory->CreateProductA();
}

void Run()
{
_abstractProductA->Show();
_abstractProductB->Show();

delete _abstractProductA;
delete _abstractProductB;
}
};

void main()
{
// Abstract factory #1
AbstractFactory* factory1 = new ConcreteFactory1();
Client* client1 = new Client(factory1);
client1->Run();

delete factory1;
delete client1;

// Abstract factory #2
AbstractFactory* factory2 = new ConcreteFactory2();
Client* client2 = new Client(factory2);
client2->Run();

delete factory2;
delete client2;

getchar();
}

/*
OUT PUT
-------
\[ProductA1\] Show
\[ProductB1\] Show
\[ProductA2\] Show
\[ProductB2\] Show
\*/

Simple LinkedList program in C++

· 3 min read

Definition:

A linked list is a data structure that consists of a sequence of data records such that in each record there is a field that contains a reference (i.e., a link) to the next record in the sequence.

#include "stdafx.h"
#include "iostream"
using namespace std;

class LinkList
{
private:
struct Node
{
int data;
Node* link;
}*p;

public:
LinkList();
~LinkList();

void Print(); // Prints the contents of linkedlist
void Append(int num); // Adds a new node at the end of the linkedlist
void Delete(int num); // Deletes the specified node from the linkedlist

void AddatBeg(int num);// Adds a new node at the beginning of the linkedlist
void AddAfter(int c, int num); // Adds a new node after specified number of nodes
int Count(); // Counts number of nodes present in the linkedlist

};

LinkList::LinkList()
{
p = NULL;
}

LinkList::~LinkList()
{
if (p == NULL)
return;

Node* tmp;
while(p != NULL)
{
tmp = p->link ;
delete p;
p = tmp;
}
}

// Prints the contents of linkedlist
void LinkList::Print()
{
if (p == NULL)
{
cout<< "EMPTY";
return;
}

//Traverse
Node* tmp = p;
while(tmp != NULL)
{
cout<data<<endl;
tmp = tmp->link ;
}
}

// Adds a new node at the end of the linkedlist
void LinkList::Append(int num)
{
Node *newNode;

newNode = new Node;
newNode->data = num;
newNode->link = NULL;

if(p == NULL)
{
//create first node
p = newNode;
}
else
{
//Traverse
Node *tmp = p;
while(tmp->link != NULL)
{
tmp = tmp->link;
}

//add node to the end
tmp->link = newNode;
}
}

// Deletes the specified node from the linkedlist
void LinkList::Delete( int num )
{
Node *tmp;

tmp = p;
//If node to be delete is first node
if( tmp->data == num )
{
p = tmp->link;
delete tmp;
return;
}

// traverse list till the last but one node is reached
Node *tmp2 = tmp;
while( tmp!=NULL )
{
if( tmp->data == num )
{
tmp2->link = tmp->link;
delete tmp;
return;
}

tmp2 = tmp;
tmp = tmp->link;
}
cout<< "nElement "<<num<<" not Found." ;
}

// Adds a new node at the beginning of the linkedlist
void LinkList::AddatBeg(int num)
{
Node *tmp;

//add new node
tmp = new Node;
tmp->data = num;
tmp->link = p;
p = tmp;
}

//Adds a new node after specified number of nodes
void LinkList::AddAfter(int c, int num)
{
Node *tmp;
Node *tmp2;
int i;
//Skip to the desired portion
for( i = 0, tmp = p; i
{
tmp = tmp->link;

//if end of linked list is encountered
if(tmp == NULL)
{
cout<<endl<< "There are less than "<<c<<" elements" ;
return;
}
}

//insert new node
tmp2 = new Node;
tmp2->data = num;
tmp2->link = tmp->link;
tmp->link = tmp2;
}

// Counts number of nodes present in the linkedlist
int LinkList::Count()
{
Node *tmp;
int c = 0;

//Traverse the entire Linked List
for (tmp = p; tmp != NULL; tmp = tmp->link)
c++;

return (c);
}

void main()
{
LinkList* pobj = new LinkList();
pobj->Append(11);
pobj->Append(22);
pobj->Append(33);
pobj->Delete(33);
pobj->AddatBeg(44);
pobj->AddAfter(1, 55);
pobj->Print();
cout<<endl<< "no. of elements in linked list="<<pobj->Count()<<endl;

delete pobj;
}

/*
OUTPUT
----------------
44
11
55
22

No. of elements in linked list = 4
*/

'Builder' Design Pattern using simple program

· One min read

Definition:

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Program:

#include "iostream"
using namespace std;

// Builder pattern -- Creational example
class Product
{
private:
char* _parts[10];
int i;

public:
Product()
{
i = 0;
}

void Add(char* part)
{
_parts[i] = part;
i++;
}

void Show()
{
cout<
for(int j = 0; j {
cout<<_parts[j]<BuildPartA();
builder->BuildPartB();
}
};

class ConcreteBuilder1 : public Builder
{
private:
Product _product;

public:
virtual void BuildPartA()
{
_product.Add("PartA");
}

virtual void BuildPartB()
{
_product.Add("PartB");
}

virtual Product GetResult()
{
return _product;
}
};

class ConcreteBuilder2 : public Builder
{
private:
Product _product;

public:
virtual void BuildPartA()
{
_product.Add("PartX");
}

virtual void BuildPartB()
{
_product.Add("PartY");
}

virtual Product GetResult()
{
return _product;
}
};

void main()
{
// Create director and builders
Director director;

ConcreteBuilder1 b1;
ConcreteBuilder2 b2;

Product p1;
Product p2;

// Construct product p1
director.Construct(&amp;b1);
p1 = b1.GetResult();
p1.Show();

// Construct product p2
director.Construct(&amp;b2);
p2 = b2.GetResult();
p2.Show();

getchar();
}

/*
OUT PUT

Product Parts:
PartA
PartB

Product Parts:
PartX
PartY
*/

Simple Queue program in C++

· One min read

Definition:

A Queue is a data structure in which addition of new element takes place at the end called rear of Queue and deletion of existing element takes place at the other end called front of Queue .

Principle:

Queue works on the FIFO – First In First Out principle

#include "stdafx.h"
#include "iostream"
using namespace std;

#define MAX 10

class Queue
{
private:
int arr[MAX];
int front, rear;

public:
Queue()
{
front = -1;
rear = -1;

}

void Add(int item)
{
if(rear == MAX-1)
{
cout<<endl<< "Queue is full";
return;
}

rear++;
arr[rear] = item;

if( front == -1 )
front = 0;
}

int Delete()
{
if(front == -1)
{
cout<<endl<< "Queue is empty";
return NULL;
}

int data = arr[front];

if( front == rear)
front = rear = -1;
else
front++;

return data;
}
};

int main()
{
Queue q;

q.Add(1);
q.Add(2);
q.Add(3);

int i = q.Delete();
cout<<endl<< "item="" deleted="<<i<<endl;

i = q.Delete();
cout<<endl<< "Item deleted = "<<i<<endl;

return 0;
}

/*
OUTPUT
----------------
Item deleted = 1

Item deleted = 2
*/

Memory Layout of a class (C++) Object

· One min read

Let us know how the members of a class are stored in the C++ class object.

  1. All Static Members Functions, Static member variables and Non static Members Functions are hoisted outside the class object.
  2. All non static member variables are stored in the class object.
  3. All virtual functions are part of Virtual Table. And a pointer (vptr) to the created Virtual Table is inserted with in each class object.

Sample Program:

class Sample
{
public:
Sample() {};

virtual ~Sample() {}
virtual void virtualFun1() {}
virtual void virtualFun2() {}

void normalFun() {}

static int getCount() //static function
{
return nCount;
}

private:
int i;
static int nCount;
};

void main()
{
Sample obj;
cout<<obj;
}

Size Matters (C++)

· 2 min read

C++ class have

A. Data Members B. Members Functions

Data Members​

  1. Static Data Member The size of a class object with only Static data members irrespective of Data Type (say float, long e.tc.) is equal to one Byte (~ size of Empty class)
    class CStaticDataMemberCls
{
public:
static int i;
static float f;
};


void main() {
CStaticDataMemberCls objSDMC;
cout<<objSDMC;
}
  1. Non Static Data Member The size of a class with non static data members is equal to sum of the data type size i.e. size of int = 4 size of float = 4 so total = 8
    class CNonStaticDataMemberCls
{
public:
int i;
float f;
};


void main() {
CNonStaticDataMemberCls objNSDMC;
cout<<objNSDMC;
}

Members Functions​

  1. Static Members Functions
  2. Non Static Members Functions

As Static Members Functions and Non static Members Functions are hoisted outside the class object. The size of the class will also be equal to one Byte (~ size of Empty class)

class CMemberFunctionsCls
{
public:
int fun1() { return 1; }
static int staticFun() { return 1; }

};

void main()
{
CMemberFunctionsCls objMFC;
cout<<objMFC;
}
  1. Virtual Members Functions If a class consists of virtual functions a table of pointers(i.e. Virtual Table) to virtual functions is generated for each class. And a pointer (vptr) to the created Virtual Table is inserted with in each class object. So the size of CVirtualFunctionCls object will be 4 Bytes which is nothing but a size of vptr.
    class CVirtualFunctionCls
{
public:
virtual ~CVirtualFunctionCls() {}
virtual void virtualFun1() {}
virtual void virtualFun2() {}
};


void main() {
CVirtualFunctionCls objVFC;
cout<<objVFC;
}

Let us see the class with all the above members

class Sample
{
public:
Sample() {};

virtual ~Sample() {}
virtual void virtualFun1() {}
virtual void virtualFun2() {}

void normalFun() {}

static int getCount() //static function
{
return nCount;
}

private:
int i;
static int nCount;
};

void main()
{
Sample obj;
cout<<obj;
}

Variable arguments handling in C/C++

· One min read

Use va_list to accept a VARYING NUMBER OF ARGUMENTS for any function in C/C++. printf(const char*_Format, ...) is a real time function which uses va_list.

For using va_list we need to know about the following macros

va_start Initialize a variable argument list (macro) va_arg Retrieve next argument (macro) va_end End using variable argument list (macro)

The sample explains how to use VARYING NUMBER OF ARGUMENTS


# include <stdarg.h>

int Add(int args, ...)
{
int sum = 0;
int temp = 0;

va_list va; //1. Declare a va_list

va_start(va, args); //2. Initialise

for(int i = 0; i<=args; i++) {
temp = va_arg(va, int); //3. Retrieve
sum = temp+sum;
}

va_end(va); //4. END

return sum;
}

void main() {
printf("sum=%d n ", Add(2, 1, 2, 5));
//OutPut: 8
}