OOAD Overview Q/A #3


Question:What is dynamic initialization of objects? Why is it required? Illustrate with an example in C++.

Answer:

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.

Need of 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.

Program example to explain the concept of dynamic initialization

#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
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements