C++ Member Initialization List

Why does the code below give an error?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Given the following code:
class A {
   int x;
   const int y;
   int& z;
public:
   A(int x = 0, int y = 0, int z = 0) 
   {
   }
};

int main(void) {
  A a;
  return 0;
}
What is the result of compilation?   Success ✘   Error ✔   Warning    Undefined 

}
A(int x = 0, int y = 0, int z = 0)
This isn't an initialization list, you're setting default values for the arguments.

This is an initialization list:
1
2
3
4
5
6
class B{
    int x, y;
public:
    B(): x(0), y(0){}
    //   ^^^^^^^^^^
};

Now, as for your code, the quirk is that you made z a reference, so you're forced to initialize it to something.
1
2
3
4
5
6
7
8
9
10
11
12
class A {
   int x;
   const int y;
   int &z;
public:
   A(int &z_param): x(0), y(0), z(z_param){}
};

int main(){
    int something;
    A a(something);
}
Topic archived. No new replies allowed.