ok quick look at dynamic memory....
You ask the operating system for a chunk of memory on the heap by using the new keyword. This returns a pointer to the given memory or either throws std::bad_alloc or returns 0 if unsuccessful (depends on compiler mostly).Dont lose this pointer because it is the key to freeing up the memory when you have finished with it.
Code:
#include<iostream>
using namespace std;
class A
{
private: int x;
public : A() : x(100) {}
print() {cout<<x;}
};
int main()
{
// lets dynamically create an instance of A
A* pointer_to_A = new A;
if(pointer_to_A)
{
pointer_to_A ->print();
//ok finished with memory so now we free it like this
delete pointer_to_A;
//but hang on pointer_to_A still points to our freed memory so for safety
pointer_to_A=NULL;
}
// ok now a dynamic array of A objects
A* pointer_to_array = new A [5];
if (pointer_to_array)
{
for(int i=0;i<5;i++)
{
pointer_to_array[i] -> print();
cout<<endl;
}
// now we are finished with it we free it like this
delete [] pointer_to_array;
pointer_to_array=NULL;
}
return 0;
}
anything there you dont follow?