Initialisation and assignment

后端 未结 6 2199
不思量自难忘°
不思量自难忘° 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:30

    One thing that nobody has yet mentioned is the difference between initialisation and assignment of class fields in the constructor.

    Let us consider the class:

    class Thing
    {
      int num;
      char c;
    public:
      Thing();
    };
    
    Thing::Thing()
      : num(5)
    {
      c = 'a';
    }
    

    What we have here is a constructor that initialises Thing::num to the value of 5, and assigns 'a' to Thing::c. In this case the difference is minor, but as was said before if you were to substitute int and char in this example for some arbitrary classes, we would be talking about the difference between calling a parameterised constructor versus a default constructor followed by operator= function.

提交回复
热议问题