Initialisation and assignment

后端 未结 6 2200
不思量自难忘°
不思量自难忘° 2020-11-29 04:16

What EXACTLY is the difference between INITIALIZATION and ASSIGNMENT ?

PS : If possible please give examples in C and C++ , specifically .

Actually , I was

6条回答
  •  既然无缘
    2020-11-29 04:46

    In the simplest of terms:

    int a = 0;  // initialization of a to 0
    a = 1;      // assignment of a to 1
    

    For built in types its relatively straight forward. For user defined types it can get more complex. Have a look at this article.

    For instance:

    class A
    {
    public:
       A() : val_(0)  // initializer list, initializes val_
       {}
    
       A(const int v) : val_(v) // initializes val_
       {}
    
       A(const A& rhs) : val_(rhs.val_)  // still initialization of val_
       {}
    
    private:
        int val_;
    };
    
    // all initialization:
    A a;
    A a2(4);
    A a3(a2);
    
    a = a3; // assignment
    

提交回复
热议问题