0

I was trying to initialize non-static member variable using parenthesis. I encountered this in Scott Meyers book (9th release) at page 50. The book says error but doesn't say why. May be I am not able to read between the lines. Is there reason why this fails. I just wanted to know the reason behind the fail.

#include <iostream>

struct B {};

struct C {
    C(int x) : val(x) {}

    int val;
};

class A {
   public:
    A(){};

   private:
    int x = 1; // fine
    int y{3}; // fine
    int z(0); // error
    B b;      // fine
    C c(4); // error
};

int main() {
    int x(5); // this works as well

    A a;
    std::cout << x << std::endl;
}
solti
  • 4,339
  • 3
  • 31
  • 51
  • 1
    I think it is to avoid ambiguities. See https://en.wikipedia.org/wiki/Most_vexing_parse – Cris Luengo Mar 10 '17 at 05:27
  • 1
    Not all forms of initialization can be used to perform in-class member initialization. That's what the standard says. Are you wondering why the standards committee made that decision? – R Sahu Mar 10 '17 at 05:32
  • @RSahu I think your first line answers my question. But me being curious .. Is Cris right about `vexing_parse`? Why did standards committee made that decision? – solti Mar 10 '17 at 05:38
  • @solti, I don't know why the standards committee made that decision. Let's hope someone that does know the reason posts an answer. – R Sahu Mar 10 '17 at 05:41

0 Answers0