Dynamic initialization states that we are initializing the objects at the runtime. Since we use constructors to initialize everything, here we are going to use dynamic constructors.
Here is an example of dynamic initialization:
#include<iostream> using namespace std; class Details { string name; int age; int rollno; public: Details(string n,int a,int r) { name=n; age=a; rollno=r; } void disp() { cout<<"The name of the Student is: " <<name<<"\n"; cout<<"The age of the Student is: " <<age<<"\n"; cout<<"The rollno of the Student is: " <<rollno<<"\n"; } }; int main() { string n; int a,r; cout<<"Please enter the name of the Student --> "; cin>>n; cout<<"Please enter the age of the Student --> "; cin>>a; cout<<"Please enter the rollno of the Student --> "; cin>>r; //Dynamically initializing Details firststudent(n,a,r); firststudent.disp(); return 0; }
Output:
Please enter the name of the Student --> neeraj Please enter the age of the Student --> 28 Please enter the rollno of the Student --> 121 The name of the Student is: neeraj The age of the Student is: 28 The rollno of the Student is: 121
This dynamic initialization can help us to create different constructors having the same function name but different parameters.
If you want to deallocate the memory then the delete operator can be used.
I hope you have understood this blog. Please do comment below if you are still facing any difficulties with the dynamic initialization of objects.
The post Dynamic Initialization of Objects in C++ appeared first on The Crazy Programmer.
from The Crazy Programmer https://ift.tt/udClbyY
Comments
Post a Comment