Wednesday, February 27, 2013

OOCP (CPP) : Example # 12 : CPP Operator New and Delete

OOCP (CPP)  :  Example #  12 : CPP Operator New and Delete.

* Lets allocate memory run time.
* new operator example using cpp language.

* delete operator example using cpp language.
//Written by Latest Technology Guide    
//Title : OOCP (CPP)  :  Example # 
 12 : CPP Operator New and Delete.


#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>

class String
{
private:
char *name;
int length;
public:
String(char *s)
{
length=strlen(s);
name = new char[length+1];
strcpy(name,s);
}
String()
{
length=0;
name = new char[length+1];
}
void display()
{
cout << "Name : " << name << endl;
}
void join(String &a, String &b);
};

//=================================================
// Join Member Function of String
//=================================================
void String :: join(String &a, String &b)
{
length = a.length + b.length;
delete name;

name = new char[length+1];
strcpy(name,a.name);
strcat(name,b.name);
}

//=================================================
// Main Function
//=================================================
void main()
{
clrscr();
String n1("MCA "),n2(" GTU "),n3("India"),s1,s2;

//main purpose of join
s1.join(n1,n2);
s2.join(s1,n3);

n1.display();
n2.display();
n3.display();
s1.display();
s2.display();

getch();
}

Output:
* You will find output as combination of string1 and string2.

--------------------------------------------------------------------------------
OOCP (CPP)  :  Example #  12 : CPP Operator New and Delete.

* Example demonstrate how to allocate memory on the go (Runtime memory allocation using cpp).
* Program demonstrate use of new operator in cpp.

Note: All programs are developed and tested using Turbo C++ 3.0 under Windows XP. We just want to provide guidelines to the users. If you are using any other Compiler or other operating system they you need to modify this program as per your requirements. 

1 comment:

  1. thank you for sharing nice article in your blog
    visit
    web tutorial programming
    https://www.welookups.com

    ReplyDelete