I am learning some basic things about classes and OOP in C++. From what I read the preferred modern way of initializing a variable is to use uniform initialization.
In the simple class header example below, uniform initialization is used to initialize the 3 data members (length, width and height).
For consistency, I thought it might be a good idea to use uniform initialization when setting default values in the constructor declaration but this does not work and the compiler (gcc 6.3 on Debian Stretch) generates and error. From what I can see the compiler thinks the curly braces {} are the start of the constructor definition body (clearly it is not since the right bracket ")" has not yet been added).
I accept this will not work but out of curiosity is there a reason why? I would prefer to be consistent with my code and use uniform initialization where ever possible.
Thanks.
#ifndef BOX_H
#define BOX_H
class Box
{
private:
double length {1.0};
double width {1.0};
double height {1.0};
public:
//constructor
Box(double l = 1.0, double w = 1.0, double h = 1.0); //ok
//Box(double l {1.0}, double w {1.0}, double h {1.0}); //Error
double volume();
};
#endif
EDIT....thanks for the comments so far but I'm not sure I understand the reason why you cannot use uniform initialization for default arguments. Is there some standard C++ documentation someone can point me to?
For example, taking the basic program below, it is ok to initialize n with a value of 5 using uniform initialization but it is not ok to initialize x like this as a default argument in the function header (I am using gcc 6.3 with -std=c++17). Why is this? Apologies if I have not understood the help so far.
#include <iostream>
void printNum(int x {1}) //error
{
std::cout<<x<<"\n";
}
int main()
{
int n {5}; //OK
printNum(n);
}