Easy tutorial for C / C ++ - class 6 (Dynamic memory
allocation 2)
- The 'new' operator is used for dynamic memory allocation in the constructor, and the 'delete' operator is used to release
the memory in the destructor. Let's look at a simple example.
Example Code
#include
<iostream>
#include
<iomanip>
using
namespace std;
class
t_Class{
private :
int n;
int *p;
public :
t_Class(int, int);
~t_Class();
void prn();
};
t_Class::t_Class(int
num, int ini){
p = new int[num];
n = num ;
for(int i = 0; i < n; i++){
p[i] = ini;
}
}
void
t_Class::prn(){
cout << " Size : " << n << endl ;
cout << " Initial values :
" << endl;
cout << endl;
for(int i = 0; i < n; i++){
cout << " p[" <<
i << "] = " << p[i] << endl;
}
}
t_Class::~t_Class(){
delete []p;
}
int
main() {
int n, v;
cout << " Size : " ;
cin >> n ;
cout << " Initial values : " ;
cin >> v ;
cout << endl;
t_Class x(n,v);
x.prn();
return 0;
}
- A class 't_Class' was declared. And integer variable
'n' as member variable and pointer variable 'p' to be used for dynamic memory
allocation were also declared.
- Let's create a constructor with two integer arguments.
The argument 'num' indicates the size of the array to be allocated dynamic
memory. The argument 'ini' represents the initial values of the array to be
created. We used 'for loop' to initialize each element of array by 'ini'.
- Use the output function 'prn ()' to check that the size
of the array and the initial value appear correctly. And in the destructor, we
use the 'delete' operator to release the allocated memory.
- Declared two integer variables 'n' and 'v' in the main
function. I will use the 'cin' object to input the size and initial value of
the array with the keyboard.
- The object 'x' is declared and given 'n' and 'v' as
arguments. Let's check the output through the output function 'prn ()'.
results
:
Size
:
- You will be prompted to enter the size of the array.
Let's enter 7 here.
Size
: 7
Initial values :
- You are prompted to enter the initial value of the
array. Enter 1 here and press Enter.
Size : 7
Initial values : 1
Size
: 7
Initial values :
p[0] = 1
p[1] = 1
p[2] = 1
p[3] = 1
p[4] = 1
p[5] = 1
p[6] = 1
- An
array of size 7 is created and the values of array elements are initialized to
1.
No comments:
Post a Comment