What do you mean by a dynamic initialization of variables?

C++Server Side ProgrammingProgramming

Dynamic initialization of object refers to initializing the objects at run time i.e. the initial value of an object is to be provided during run time. Dynamic initialization can be achieved using constructors and passing parameters values to the constructors. This type of initialization is required to initialize the class variables during run time.

Why we need the dynamic initialization?

Dynamic initialization of objects is needed as

  • It utilizes memory efficiently.

  • Various initialization formats can be provided using overloaded constructors.

  • It has the flexibility of using different formats of data at run time considering the situation.

Example Code

#include <iostream>
using namespace std;
class simple_interest {
   float principle , time, rate ,interest;
   public:
      simple_interest (float a, float b, float c) {
         principle = a;
         time =b;
         rate = c;
      }
      void display ( ) {
         interest =(principle* rate* time)/100;
         cout<<"interest ="<<interest ;
      }
};
int main() {
   float p,r,t;
   cout<<"principle amount, time and rate"<<endl;
   cout<<"2000 7.5 2"<<endl;
   simple_interest s1(2000,7.5,2);//dynamic initialization
   s1.display();
   return 1;
}

Output

Enter principle amount ,rate and time
2000 7.5 2
Interest =300
raja
Published on 28-May-2019 16:18:58
Advertisements