Monday, 14 April 2014

CLASS DESIGN IN C++ USING DYNAMIC MEMORY ALLOCATION, DESTRUTOR, COPY CONSTRUTOR


CLASS DESIGN IN C++ USING DYNAMIC MEMORY ALLOCATION, DESTRUTOR, COPY CONSTRUTOR


Ex: No: 3 CLASS DESIGN IN C++ USING DYNAMIC MEMORY ALLOCATION, DESTRUTOR, COPY CONSTRUTOR

Aim:To write a c ++ program to implement the dynamic memory allocation, destructor, and copy constructor

Algorithm:

Step 1: Start the program.
Step 2: Create class string with two constructors the first is an empty constructor, which allows declaring an array of string, the second constructor initiates the length of the string and allocates unnecessary space for the string to the stored and create the string itself.
Step 3: Then destruct and create a member to concentrate two strings.
Step 4: Destruct the string using the symbol (~)
Step 5: Declare the main function using and display the string S1, S2 and display destructor data and display the concatenate string S3 display, the copy constructed string S4.
Step 6: Stop the program.

Program:

#include
#include
#include
int count=0;
class string
{
private:
char*str;
public:
string(char*s)
{
count++;
int len=strlen(s);
str=new char[len+1];
strcpy(str,s);
}
string()
{
delete str;
}
void display()
{
cout<
}
void concat(string s1,string s2)
{
int len;
len=strlen(s1.str)+strlen(s2.str);
str=new char[len+1];
strcpy(str,s1.str);
strcat(str," ");
strcat(str,s2.str);
}
~string()
{
cout<<"no of object destroyed"<
count--;
}
};
int main()
{
clrscr();
string s1="SUPER";
string s2="STAR";
string s3;
string s4(s1);
s1.display();
s2.display();
s3.concat(s1,s2);
s3.display();
s4.display();
getch();
return(0);
}
Output:

SUPER
STAR

Number of object destroyed 0x8fce 0390
Number of object destroyed 0x8fce 0390

SUPER STAR
STAR

Result:

Thus the implementation of c ++ program for the dynamic memory allocation, destructor and copy constructor is executed and the output has been verified.



0 comments:

Post a Comment