C++ program to implement Constructors and destructors. default, copy, dynamic constructor with memory allocation using new command for 1-d and 2-d arrays.
PROGRAM:
#include<iostream.h>
#include<iostream.h>
#include<conio.h>
class code
{
int id;
public:
code()
{
}
code(int
a)
{
id = a;
}
code(code
&x) // copy constructor
{
id = x.id; // copy in the value
}
void
display (void)
{
cout<<id;
}
};
void main()
{
clrscr();
code A(100); // object A is created and
initialized
code B(A); // copy constructor called
code C = A; // copy constructor called again
code D; // D is created, not initialized.
D
= A; // copy constructor not called
cout <<"\n id of A: ";
A.display();
cout <<"\n id of B: ";
B.display();
cout <<"\n id of C: ";
C.display();
cout <<"\n id of D: ";
D.display();
getch();
}
OUTPUT
id
of A: 100
id
of B: 100
id
of C: 100
id
of D: 100
>>>Dynamic constructor with memory
allocation using new command for 1-d array
Program
Code:
#include<iostream.h>
#include<string.h>
#include<conio.h>
class string
{
char
*name;
int
length;
public:
string()
{
length = 0;
name=new char[length+1]; //one extra for \0
}
string
(char *s)
{
length = strlen(s);
name = new char[length+1];//one extra for \0
strcpy (name,s);
}
void
display()
{
cout<<name<<endl;
}
void
join (string &a,string &b);
};
void string :: join(string &a, string
&b)
{
length
= a.length + b.length;
delete
name ;
name
= new char[length+1]; //dynamic allocation.
strcpy(name,a.name);
strcat(name,b.name);
};
void main ()
{
clrscr();
char
*first = "Joseph ";
string
name1(first),name2("Louis "),name3("Lagrange"),s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
getch();
}
OUTPUT
Joseph
Louis
Lagrange
Joseph Louis
Joseph Louis Lagrange
>>>Dynamic constructor with memory
allocation using new command for 2-d arrays
Program
Code:
#include<iostream.h>
#include<conio.h>
class matrix
{
int
**p; //pointer to matrix
int
d1,d2; //dimensions
public:
matrix(int
x, int y)
{
d1 = x;
d2 = y;
p = new int *[d1]; //creates an array pointer
for(int i = 0; i < d1; i++)
p[i] = new int [d2]; //creates space for each
row
}
void
get_element(int i, int j, int value)
{
p[i][j]
= value;
}
int
& put_element(int i, int j)
{
return
p[i][j];
}
};
void main ()
{
clrscr();
int
m,n;
cout
<<"Enter size of matrix : ";
cin
>> m >> n;
matrix A(m, n); // matrix object A constructed
cout
<<"Enter matrix elements row by row \n";
int
i,j,value;
for
(i = 0; i < m; i++)
for
(j = 0; j< n; j++)
{
cin >> value;
A.get_element(i,j,value);
}
cout
<<endl;
cout
<< A.put_element(1,2);
getch();
}
OUTPUT
Enter size of matrix : 3 4
Enter matrix elements row by row
11 12 13 14
15 16 17 18
19 20 21 22
17