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 FIFOFirst 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
*/

C FAQ 4 to 7: Simple Programms

· One min read

4. Swap of two numbers  with out temp

#include "stdio.h";

int main()
{
int a,b;
a=10;
b=20;
printf("Before swapingn");
printf("%dt%dn",a,b);

/* normal temp
int temp;
temp=a;
a=b;
b=temp;

//sol:-1
a=a+b;
b=a-b;
a=a-b;

//sol:-2
a=ab;
b=a/b;
a=a/b;/

//sol:-3
//a^=b^=a^=b;

a= a^b;
b= a^b;
a= a^b;
printf("%dt",a);
printf("After swapingn");
printf("%dt%dn",a,b);
return 0;
}

Read More

Tags:

Write a code to Outputs its own code

· One min read

FILE macro is a Predefined Macros : The name of the current source file. FILE expands to a string surrounded by double quotation marks.

fgetc: Read a character from a stream. returns an integer putchar: Writes a character to a stream

# include "stdio.h"
//Program that outputs its own code

int main () {
FILE *fp; char c;
fp = fopen(__FILE__,"r");

while((c=getc(fp))!= EOF) {
printf("%c",c);
}
fclose(fp);
}
Tags:

Change the name of the Debug Version of a DLL or Exe

· One min read

Its very useful to name the Debug version of the exe or DLL with letter "D" appended inoder to avoid confisuion between release and debug version of binaries

Steps:

  1. Create a console application with name "MyProject"

  2. To change the output file name in debug configuration

place D as shown in below figure

Project Project Properties -> Linker -> General -> Output File

Release Version: MyProject Application Name: c:MyProjectReleaseMyProject.exe Debug Version: MyProject Application Name: c:MyProjectDebugMyProjectD.exe