
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What do you mean by a dynamic initialization of variables?
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 runtime. 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 runtime.
Why do we need the dynamic initialization?
Dynamic initialization of objects is useful because
- 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.
Examples of Dynamic Initialization of Variable
In this example, we directly pass the values of principal, amount, and rate i.e., 2000, 7.5, and 2, to calculate the operation of simple interest class when creating the object s1. So, these values are dynamically initialized at runtime using the parameter.
#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; //dynamic initialization simple_interest s1(2000,7.5,2); s1.display(); return 1; }
The above code produces the following result:
Principle amount, time and rate 2000 7.5 2 interest =300
Advertisements