Dynamic Memory Allocation In C++

 Dynamic Memory Allocation In C++

What is dynamic memory allocation?

Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack

Why we use Dynamic Memory Allocation?

Dynamic Memory Allocation is to allocate memory of variable size which is not possible with compiler allocated memory except variable length arrays. The most important use of dynamic memory allocation is the flexibility as the programmers are free to allocate and deallocate memory whenever we need and when we don't.

**I AM KEEP IMPORVING THIS ARTICLE**

#include<iostream>
using namespace std;
class simple
{
 int *p; // defining a pointer as we are going to work with dma
 public:
 simple(int x) // Parameterized constructor
 {
 // allocating dynamic memory
 cout<<"I am paramertized constructor"<<endl;
 p=new int ; //new int will return the dynamically created adress
 *p = x; // x value is stored in *p i.e. value stored in p.
 }
 
 simple(simple &obj) // USER DEFINED COPY CONSTRUCTOR
 {
 cout<<"I am copy constructor"<<endl;
 // now copying the values of object 1 variable to object 2 variable.
 p=new int()
 *p=*obj.p
 
 }
 void disp() // for diplaying values
 {
 cout<<"The value is : "<<*p<<endl;
 cout<<"I will give the adress of varaible : "<<p<<endl;
 // we will se that for each value address is different
 }
};
int main()
{
 simple s1(10);
 simple s2(s1);
 s1.disp();
 s2.disp();
 return 0;

Comments

Popular posts from this blog

Array Of Objects In C++ | Array Of Objects Explained With Real Life Example

Pointers In C++ | Pointer Explained With Real Life Examples | Pointers In OOPs C++

Destructor In C++ | Destructor Explained With Real Life Examples