0

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();
    }
    
} 
Aamir
  • 1,974
  • 1
  • 14
  • 18
user_xyz
  • 3
  • 2

1 Answers1

1

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.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175