Dynamic Constructor
- Dynamic constructor is used to allocate the memory to the objects at the run time.
- Memory is allocated at run time with the help of 'new' operator.
- By using this constructor, we can dynamically initialize the objects.
Example:
#include <iostream.h>
#include <conio.h>
class dyncons
{
int * p;
public:
dyncons()
{
p=new int;
*p=10;
}
dyncons(int v)
{
p=new int;
*p=v;
}
int dis()
{ return(*p);
}
};
void main()
{
clrscr();
dyncons o, o1(9);
cout<<"The value of object o's p is:";
cout<<o.dis();
cout<<"\nThe value of object 01's p is:"<<o1.dis();
getch();
}
Output:
The value of object o's p is:10
The value of object 01's p is:9
Ask Question