Home > Blockchain >  why we can't initiaize data member in a member function using list initializer?
why we can't initiaize data member in a member function using list initializer?

Time:09-01

why assignment is working, but initialization not working ? please explain what is happening in these 3 cases in code.

#include <iostream>

class Fun {
public:
    void set_data_variable()
    {
        y {2};      // case 1 : this doesn't work
        // y = 2;   // case 2 : this does work
        // y = {2}; // case 3:  this also work

        std::cout << y << "\n";
    }
private:
     int y = 6;
};

int main()
{
    Fun f;
    while (1) {
        f.set_data_variable();
    }
    
} 

CodePudding user response:

For intrinsic type (And also user defined classes) this syntax:

y {2};

Is only valid during object construction. The object y has already been constructed. It happened in the compiler generated function Fun() (The default constructor of the Fun class).

y = 2; and y = {2}; work because they are assignment operations.

  • Related