What is dynamic initialization of object in c++?

前端 未结 4 1126
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 07:11

What is dynamic initialization of objects in c++?

Please explain with an simple example...

4条回答
  •  北海茫月
    2020-11-28 07:49

    Dynamic initialization means the first value assigned to the variable after memory allocation is not known at compile time, it is evaluated only at run time. for example

    #include 
    
    using namespace std;
    
    int sample()
    {
        int x;
        cin >> x;
        return x;
    }
    
    const int t = sample(); //dynamic initialization
    
    int p = sample();       //dynamic initialization
    
    void main()
    
    {
    
        cout << t;
    
        cout << p;
    
    } 
    

    As we know that a constant can get value only once i.e. at the time of initialization. this example shows that even a global variable which is static storage if dynamically initialize by return value of a function, the first value assigned to the variable is the value returned by function, which replaces the initial default value 0 of the variable which is assigned at the time of memory allocation.

提交回复
热议问题